Advanced · 12 min
Closures and private state
Keep independent state inside functions returned by a factory.
Retain the enclosing scope
A closure lets a function access the surrounding scope where it was created, even after the outer function has returned.
function createCounter() {
let count = 0;
return () => { count += 1; return count; };
}
const next = createCounter();
console.log(next());
console.log(next());Output
1 2
Create independent instances
Each factory call creates its own state. Sharing a returned function shares that state; calling the factory again creates a separate one.
function createCounter() { let count = 0; return () => ++count; }
const first = createCounter();
const second = createCounter();
first();
console.log(first());
console.log(second());Output
2 1
Put it into practice
- Predict each result before running the example.
- Complete the coding task, then explain why your solution works.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Create a step counter
Make each call add step to the private value. Display the results of two calls with step equal to 3.
Use step when updating value inside the returned function.