Nested Scopes
What you'll learn: How JavaScript resolves variable names when functions or blocks are nested inside each other.
When you place a function inside another function, or a block inside a block, you create nested scopes. JavaScript looks for variables starting in the innermost scope, then works its way outward through each parent scope until it finds the name or reaches global scope.
Think of it like looking for a book: you check your desk first, then your room, then the living room, then the library. You stop searching as soon as you find it.
How the Scope Chain Works
let outer = "I'm outside";
function parent() {
let middle = "I'm in the middle";
function child() {
let inner = "I'm inside";
console.log(inner); // ✓ Found immediately
console.log(middle); // ✓ Found in parent scope
console.log(outer); // ✓ Found in global scope
}
child();
}
parent();
The child function can access inner, middle, and outer because it lives inside parent, which lives in global scope. But parent cannot access inner—scope only flows inward, never outward.
With Blocks
let a = 1;
if (true) {
let b = 2;
if (true) {
let c = 3;
console.log(a, b, c); // 1 2 3 - can see all three
}
// console.log(c); // Error! c doesn't exist here
}
Each nested block can see variables from its outer blocks, but not vice versa.
Key Takeaway: JavaScript searches for variables from the current scope outward through parent scopes, creating a "scope chain." Inner scopes can read outer variables, but outer scopes cannot access inner variables.