Scope, Closures & Private State
Control where values live, keep state private with closures, and decide when that state should be released.
By the end, you’ll be able to…
- Trace how function scope and block scope limit where a name can be read.
- Explain lexical scope and build closures with factory functions.
- Keep mutable state private and recognize when a closure holds memory.
01Scope is a one-way window
Scope is the region where a name is visible. A function creates its own scope, and let and const create block scope inside braces. The braces of an if statement are enough to create that smaller region. An inner function can read names from its outer function, but the outer function cannot read names declared inside the inner one. This one-way visibility keeps implementation details from leaking.
Prefer const for bindings that never need reassignment and let for values that change. Avoid var in new code because it ignores block boundaries and is hoisted with an initial value of undefined. A variable declared in the smallest scope that still works is easier to name, test, and eventually delete. When in doubt, start inside the block and move a declaration outward only when another scope genuinely needs it.
02Lexical scope follows the source, not the call
JavaScript uses lexical scope: a function looks up names where it was written, not where it was called. When you pass a function to another part of the program, it still remembers the environment of its definition. A callback passed to an array method or a timer still sees the variables from the file or function where it was created. That rule is the foundation of closures.
A closure is a function together with the variables it references from an outer scope. The inner function can keep using those variables after the outer function has returned. Each call to the outer function creates a fresh environment, so two closures made by the same factory do not share state. The returned function does not copy the value at creation time; it reads the current binding whenever it is called.
03Closures can keep state private
A factory function returns an object whose methods close over local variables. Those variables are not properties of the object, so outside code cannot read or assign them directly. The methods become the only supported way to change the state, which forms a small public interface around a hidden implementation.
This pattern is useful for counters, caches, and small modules. It also prevents accidental global state, where unrelated functions read and overwrite the same name. The cost is that the state is invisible in a debugger unless you expose a read-only method or getter.
04Closures and memory
A closure keeps referenced variables alive for as long as the closure itself is reachable. That is what preserves a counter between calls, but it also means a large array captured by a long-lived callback cannot be garbage-collected. Capture only what the function needs.
Closures are not a leak by themselves. A leak appears when a closure is stored somewhere permanent, such as a global listener or an ever-growing array, and it retains a large object graph. A page that creates thousands of counters and never drops them keeps all of their captured state alive. Remove listeners and clear caches when their work is finished, and expose a reset method when state should be discarded.
The ideas worth keeping.
- Block scope and function scope limit names to the region where they are useful.
- A closure is a function plus the outer variables it remembers.
- Factory functions keep state private, but captured values stay in memory while the closure is reachable.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: A counter with three methods
Write makeCounter(start = 0) returning increment, decrement, and value methods. The count must be private and each counter independent. Create two counters, change them differently, and print both values.
Explore a worked solution
function makeCounter(start = 0) { let count = start; return { increment() { count += 1; return count; }, decrement() { count -= 1; return count; }, value() { return count; }, };}const saved = makeCounter(10);const alerts = makeCounter();saved.increment();saved.increment();alerts.decrement();console.log(saved.value());console.log(alerts.value());Each call to makeCounter creates a new count variable and a new set of methods that close over it. The output is 12 and -1. There is no way to assign saved.count from outside because count is not a property.
Exercise 2: Run a function only once
Write once(fn) that returns a wrapper. The first call runs fn with the supplied arguments and caches the result; later calls return the cached result without running fn again. Test it with a function that logs when it runs.
Explore a worked solution
function once(fn) { let called = false; let result; return function (...args) { if (!called) { result = fn(...args); called = true; } return result; };}const initialize = once(function (name) { console.log('Initializing ' + name); return { ready: true };});console.log(initialize('reports'));console.log(initialize('reports'));The closure stores called and result between invocations. The first call logs Initializing reports and returns the object; the second call returns the same object without logging because called is already true.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Exercise 1: A counter with three methods
Write makeCounter(start = 0) returning increment, decrement, and value methods. The count must be private and each counter independent. Create two counters, change them differently, and print both values.
12 -1
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
One lesson closer.
Reading is a start. Trying it yourself makes the connection.