Nested Functions and Scope Access
You'll learn: How inner functions can "see" variables from all their containing scopes, forming the foundation of closures.
The Core Idea
When you define a function inside another function, the inner function has access to its own variables, plus all variables from the outer function, plus the global scope. This creates a chain of accessible environments — the inner function can reach "outward" through each containing scope.
Think of nested functions like Russian nesting dolls: the innermost doll can see and touch everything around it, but the outer dolls can't reach inward to see what the inner doll contains.
How It Works
function outer() {
const outerVar = 'I am from outer';
function inner() {
const innerVar = 'I am from inner';
console.log(innerVar); // ✅ Can access own variable
console.log(outerVar); // ✅ Can access outer's variable
}
inner();
// console.log(innerVar); // ❌ outer can't access inner's variables
}
outer();
// "I am from inner"
// "I am from outer"
The inner function can access outerVar because of lexical scope — it looks up the scope chain until it finds what it needs.
Multiple Levels
const global = 'global scope';
function level1() {
const var1 = 'level 1';
function level2() {
const var2 = 'level 2';
console.log(global, var1, var2); // ✅ Access all three!
}
level2();
}
level1(); // "global scope level 1 level 2"
Key Takeaway: Inner functions can access variables from all containing (outer) scopes, but outer functions cannot access variables from inner scopes. This one-way visibility up the scope chain is what makes closures possible.