Reading Closure State from Outside
What you'll learn: You'll understand why code outside a closure cannot directly access the variables trapped inside it.
The Core Idea
When a function creates a closure over variables, those variables become private to that closure. The outer code that calls the function has no direct way to peek inside and read or modify those captured variables. Only the closure itself—the inner function that was created in that lexical environment—has access.
Think of a closure like a locked diary. The outer world can call the diary's functions (like "tell me today's entry"), but it can't flip through the pages directly. The diary controls what information it shares.
Why This Happens
JavaScript's lexical scope rules determine visibility at parse time. Variables inside a function's scope are only accessible to code written inside that scope. Once the function returns, the outer code is back in its own scope—it never had access to those inner variables and still doesn't, even though the closure keeps them alive.
function createCounter() {
let count = 0; // Private variable
return function() {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
// Cannot do this:
// console.log(count); // ReferenceError: count is not defined
// console.log(counter.count); // undefined
The variable count lives only in the closure's scope. The outer code can invoke the closure to indirectly interact with count, but it cannot read or write count directly.
Key Takeaway: Outer code cannot directly access variables inside a closure—only the closure function itself can read or modify them, making those variables effectively private.