Function scope
Learn that variables declared inside a function are not accessible from outside.
Function scope
When you declare a variable inside a function, it becomes local and lives only inside that function. When the function ends, the local variable disappears.
This lets each function keep its own private space. In function add(a, b) { let sum = a + b; return sum; }, sum can only be read inside add; reaching it from outside throws an error.
Local variables and the scope principle
The reason local variables cannot be reached from outside is the scope principle: each scope creates its own variables, and outer scopes cannot see the variables of inner scopes. Access goes from outside in; it is closed from inside out.
So a function can read a total declared outside it, but code outside cannot read a total declared inside the function. This prevents you from accidentally changing another function's variable and keeps the code safer.
Exercise Compute with a local variable
Define a function called multiply(a, b). Inside it, create a local variable named result holding the value a * b, and return result. Then assign the result of multiply(6, 7) to a variable answer and log it with console.log(answer).
Show example solution
function multiply(a, b) {
let result = a * b;
return result;
}
const answer = multiply(6, 7);
console.log(answer);
Test yourself
-
What does this code output?
function make() { let item = 'pencil'; return item; } console.log(item);- pencil
- undefined
- ReferenceError
- null
Show answer
ReferenceError — Correct. item is local to the function, so it cannot be reached from outside.
-
Complete the local variable
function add(a, b) { let sum = a + b; return ____; }Show answer
function add(a, b) { let sum = a + b; return sum; } -
Match the access
- Inner to outer variable
- Accessible
- Outer to inner variable
- Not accessible
- Two vars in same scope
- See each other
- Local after function ends
- Goes away