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 n on its first call
  • Returns n + 1 on its second call
  • Returns n + 2 on 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()); // 12

This 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
JavaScript Closure Visualizationfunction createCounter(n) { ... }Outer function creates the closure environment๐Ÿ”’ Private Closure Scopecount10Initial ValueReturned FunctionCall 1โ†’ 10Call 2โ†’ 11Call 3โ†’ 12Each call accesses private countAccess๐ŸŽฏ Key Insight: Closure = Function + Private EnvironmentThe inner function maintains access to outer variables even after outer function returns
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.
Asked in
Meta 45 Google 38 Amazon 42 Microsoft 35
68.5K Views
High Frequency
~8 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen