Magicsheet logo

Counter

Easy
77.3%
Updated 6/1/2025

Counter

What is this problem about?

The Counter interview question is a fundamental JavaScript/TypeScript problem. You are asked to write a function that takes an integer nn and returns a "counter" function. This returned function, when called for the first time, should return nn. For every subsequent call, it should return the previous value plus one (n+1n+1, then n+2n+2, and so on).

Why is this asked in interviews?

Tech giants like Google and Meta use the Counter coding problem to test a candidate's understanding of Closures. Closure is a core concept in functional programming where an inner function has access to the variables of its outer function even after the outer function has finished execution. This problem is a quick way to verify if a candidate knows how to maintain state without global variables.

Algorithmic pattern used

This problem uses the Closure pattern.

  1. Define a parent function that accepts an initial value.
  2. Inside the parent, define a local variable to store the "current" state.
  3. Return a child function that increments this local variable and returns the old (or new) value.

Example explanation

Initialize createCounter(10).

  • Call 1: Returns 10. Internally, the state moves to 11.
  • Call 2: Returns 11. Internally, moves to 12.
  • Call 3: Returns 12. The counter "remembers" its progress because the returned function maintains a reference to the environment in which it was created.

Common mistakes candidates make

  • Global Variables: Using a global variable to track the count, which would lead to bugs if multiple counters were created.
  • Increment Logic: Returning n+1n+1 on the very first call instead of nn.
  • Syntactic confusion: Misunderstanding the requirement to return a function rather than a number.

Interview preparation tip

Closures are the backbone of many design patterns in JavaScript (like the Module pattern). Be prepared to explain exactly where the state is being stored in memory.

Similar Questions