Chapter IX · Scope
Function Scope
Every function call creates its own scope. Variables declared inside a function with var, let, or const are only visible inside that function — not to the code that called it, and not to sibling functions.
01 How It Works
Think of each function call as renting a private office for the duration of the call — what's inside stays inside, and the office is cleared out the moment the call ends.
Function scope is created fresh every time the function runs, and it disappears once the function finishes (unless something — like a closure — keeps a reference to it alive). Parameters are also function-scoped: they behave like variables declared at the very top of the function body. Note that var is only function-scoped, not block-scoped — a var declared inside an if or for block inside a function is still visible everywhere in that whole function, which is one of the reasons let and const were introduced.
function setup() {
let secret = "hidden";
console.log(secret); // "hidden" — visible inside setup()
}
setup();
console.log(secret); // ReferenceError — not visible out here
1. A function is called, and a brand-new function scope is created for that call.
2. Parameters and any var/let/const declared in the function body belong to this scope.
3. When the function returns, that scope is discarded (unless a closure keeps it alive).
02 Practical Example
Here is how you might see this concept applied in real-world code:
function calculate() {
let tempResult = 42;
return tempResult * 2;
}
console.log(calculate()); // 84
// A common surprise: var ignores block boundaries within a function.
function loop() {
for (var i = 0; i < 3; i++) {}
console.log(i); // 3 — var "i" leaked out of the for-block,
// but it's still trapped inside loop()'s function scope
}
loop();
Key Takeaway
Function scope is created per call and destroyed when the call ends — and remember that var ignores block boundaries, spilling out to the whole enclosing function.