Chapter IX · Scope
What is Scope?
Scope is the set of rules that determines where a variable can be seen and used in your code. Every variable belongs to some scope, and that scope decides who can read it and who can't.
01 How It Works
Think of scope like a set of rooms inside rooms inside a building. Someone standing in an inner room can shout through the open doorways and be heard in every room that contains theirs — but someone in an outer room can't see into a room they're not standing in.
JavaScript decides what's visible where based on where code is physically written — not based on which function happens to call which. This is called lexical (or static) scoping, and it's true regardless of how or when a function is actually invoked. Scope exists at several nested levels: global scope (the outermost layer), function scope (created by every function call), and block scope (created by let/const inside any {} pair). Together they form a hierarchy: inner scopes can see outward into the scopes that contain them, but outer scopes can never see inward into a scope they don't contain.
let globalVar = "visible everywhere";
function test() {
let localVar = "visible only inside test";
console.log(globalVar); // OK — outer variables are visible inward
}
console.log(localVar); // ReferenceError — inner variables are NOT visible outward
1. JavaScript reads your source code and notices where each function and block begins and ends.
2. Every variable declaration is attached to the scope it was declared in — global, function, or block.
3. When code tries to use a variable, the engine looks in the current scope first, then walks outward through each containing scope until it finds a match (or runs out of scopes and throws).
02 Practical Example
Here is how you might see this concept applied in real-world code:
if (true) {
let x = 10;
console.log(x); // 10 — accessible here, inside the block
}
console.log(typeof x); // "undefined" — x doesn't exist out here at all
Key Takeaway
Scope is decided by where code is written, not by which function calls which — an inner scope can always see out, but an outer scope can never see in.