Create a Counter Function

easy
By FrontendAtlas Editorial · Updated Nov 12, 2026
Implement createCounter(n), which returns a counter function. Its first call returns n, and each later call returns one more than the call before. The count lives in a closure, so two counters never share it, and starting values can be negative.

Arguments

  • n: number — The starting integer for the counter.

Returns

Function — A function that returns the current integer and then increments its internal state for the next call.

Solution idea

This is a classic closure exercise: the state lives in the outer scope, and only the returned functions can mutate or read it.

Examples
// Example 1
const counter = createCounter(10);
counter(); // => 10
counter(); // => 11
counter(); // => 12

// Example 2
const counter = createCounter(-2);
counter(); // => -2
counter(); // => -1
counter(); // => 0

Public interview reports

These public, self-reported interview accounts informed this practice version. The exercise is modelled on reported rounds, not copied from them, and the reports are not verified official questions or endorsements.

Reported in a public ServiceNow interview account. ServiceNow frontend interview questions