Counter Function
Prompt
Write a function called createCounter that takes an optional starting value and returns a counter function. Each time the counter function is invoked, it should return the current count and then increment it for the next call. If no starting value is provided, the counter begins from zero.
Playground
Use a variable inside the outer function to store the current count. The inner function will "close over" this variable and remember it between calls.
The post-increment operator (count++) returns the
current value before incrementing. This lets you return
and advance the counter in a single expression.
Solution
Explanation
This is one of the most fundamental closure examples you'll see in interviews, and it's a great warmup problem because the code is short but the concept is deep.
When you call createCounter(), it sets up a local variable count and returns a new function. That inner function has access to count even after createCounter has finished running. Every time you call the returned function, it reads count, returns it, and bumps it up by one for next time.
function createCounter(startValue = 0) {
let count = startValue;
return function () {
return count++;
};
}The magic is in the post-increment operator (count++). This operator does two things in one expression: it returns the current value of count, and then increments it. So the first call returns 0 and sets count to 1. The second call returns 1 and sets count to 2. And so on. If you used ++count (pre-increment) instead, you'd get 1 on the first call, which isn't what we want.
We use a default parameter (startValue = 0) to handle the case when no starting value is provided. This is cleaner than using startValue || 0, which would actually break if someone intentionally passed 0 (since 0 is falsy in JavaScript). Default parameters only kick in when the argument is undefined, which is exactly the behavior we want.
Each call to createCounter creates a completely separate closure. So createCounter() and createCounter(10) produce two independent counters with their own private count variable. They don't interfere with each other at all.
Why closures matter for interviews
Closures are one of the most frequently tested JavaScript concepts because they reveal whether a candidate truly understands how scope and memory work. This counter pattern is the simplest illustration, but the same principle powers event handlers, module patterns, memoization, and much more.