Scope and Closures Preview
What you'll learn: How lexical scope enables functions to remember variables from their creation context.
Functions That Remember
You've learned that lexical scope means a function's scope is determined by where it's written in the code. Here's something powerful: functions don't just look up variables in outer scopes—they can remember those variables even after the outer function has finished executing.
When a function "remembers" variables from its creation context, we call this a closure. It happens automatically in JavaScript whenever a function accesses variables from an outer scope.
How It Works
Think of it like this: when you create a function inside another function, the inner function carries a "backpack" with it. This backpack contains references to any variables from the outer function that the inner function uses. Even after the outer function finishes running, the inner function still has access to its backpack.
function outer() {
let message = "Hello";
function inner() {
console.log(message); // inner "remembers" message
}
return inner;
}
let myFunction = outer(); // outer has finished executing
myFunction(); // Still prints "Hello"!
The inner function was created inside outer, where message exists. Because of lexical scope, inner can access message. The closure is what keeps message alive even after outer has returned.
Why This Matters
This behavior isn't a special feature you turn on—it's how JavaScript naturally works because of lexical scope. You've already been using the scope chain; closures are simply what happens when functions preserve that chain.
Key Takeaway: Closures occur when a function remembers variables from its outer scope, even after that outer scope has finished executing—a direct result of lexical scoping.