Counter - Problem
In JavaScript, creating functions with persistent state is a fundamental concept that demonstrates the power of closures. Your task is to create a counter function that maintains its own internal state.
The Goal: Given an integer n, return a counter function that:
- Returns
non its first call - Returns
n + 1on its second call - Returns
n + 2on its third call - And so on...
Example: If n = 10, the returned function should behave like this:
const counter = createCounter(10);
console.log(counter()); // 10
console.log(counter()); // 11
console.log(counter()); // 12This problem explores closures, function scope, and state management - core concepts for understanding JavaScript's functional programming capabilities.
Input & Output
example_1.js โ Basic Counter
$
Input:
n = 10
โบ
Output:
[10, 11, 12]
๐ก Note:
The counter starts at 10 and increments by 1 with each call: counter() returns 10, then 11, then 12.
example_2.js โ Negative Start
$
Input:
n = -2
โบ
Output:
[-2, -1, 0]
๐ก Note:
The counter can start with negative numbers. Starting at -2: counter() returns -2, then -1, then 0.
example_3.js โ Zero Start
$
Input:
n = 0
โบ
Output:
[0, 1, 2]
๐ก Note:
Edge case with zero as starting point: counter() returns 0, then 1, then 2.
Constraints
- -1000 โค n โค 1000
- At most 1000 calls will be made to counter()
- Function should maintain state between calls
- Each call should return exactly 1 more than the previous call
Visualization
Tap to expand
Understanding the Visualization
1
Setup Phase
createCounter(10) creates a new 'dressing room' with count = 10
2
Return Function
The inner function is like giving someone a key to that specific dressing room
3
First Call
counter() enters the dressing room, finds count = 10, returns it, then changes it to 11
4
Subsequent Calls
Each call uses the same private dressing room, finding the updated count value
Key Takeaway
๐ฏ Key Insight: Closures allow functions to remember their creation environment, enabling elegant state management without global variables or classes.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code