Nested Functions and Scope
You'll learn how functions defined inside other functions can access variables from their outer function.
What Are Nested Functions?
In JavaScript, you can define a function inside another function. The inner function has access to its own variables, plus all the variables from the outer function. This creates a "scope chain" — the inner function can see outward, but the outer function cannot see inward into the inner function's variables.
How It Works
Think of nested functions like rooms within a house. If you're standing in an inner room, you can reach out to grab things from the outer room. But someone standing in the outer room cannot reach into the inner room to grab your things.
function outer() {
var outerVar = "I'm outside!";
function inner() {
var innerVar = "I'm inside!";
console.log(outerVar); // Can access outerVar
console.log(innerVar); // Can access innerVar
}
inner(); // Logs: "I'm outside!" then "I'm inside!"
// console.log(innerVar); // ERROR! Can't access innerVar here
}
outer();
The inner function can "see" outerVar because it's in the outer scope. But outer cannot see innerVar — that belongs only to inner.
Why This Matters
This scope behavior lets you hide implementation details and create helper functions that only exist where needed. The inner function stays private to the outer function.
Key Takeaway: Functions defined inside other functions can access outer variables, creating a scope chain from inner to outer, but not the reverse.