Predict Closure Output
Predict Output Medium
Question
What does this code print?
Code
function makeCounter() {
let count = 0;
return () => ++count;
}
const counter = makeCounter();
console.log(counter());
console.log(counter());
console.log(counter());
Hint
The inner function remembers count from the outer scope.
Explanation
makeCounter creates a local count variable and returns an arrow function that increments and returns it. Each call to counter() increments the same count variable (captured by the closure): first call returns 1, second returns 2, third returns 3. The count variable is private — only accessible through the closure.
Related Resources
Related Lessons
- JavaScript Functions
Learn about closures.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.