FrontendAtlas
Interview Questions
Home>JavaScript interview questions> JavaScript coding challenges >Create a Counter Function

Create a Counter Function

easy
By FrontendAtlas Editorial · Updated Jan 30, 2026
Support an optional initial value and keep the API simple so consumers can call inc/dec/get without exposing the internal state. Mention closure behavior, edge cases like negative increments, and tests for independent counters and performance.

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.
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

Solution

Overview

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

1

Approach: Closure-based counter (recommended)

Optionally allow a reset method if the prompt mentions it. Emphasize that the counter is deterministic: the same sequence of calls always produces the same values. Complexity is O(1) per call.

export default function createCounter(n) {
  return function() {
    const current = n;
    n += 1;
    return current;
  };
}
export default function createCounter(n: number): () => number {
  return function(): number {
    const current = n;
    n += 1;
    return current;
  };
}

Notes & Pitfalls

Pitfalls
  • Using a global variable will share state across all counters — use a closure per instance.
  • Returning `++n` vs. current value changes behavior (off-by-one). This task expects returning the current and then incrementing.
  • Mutating objects captured in closures can cause shared state; here we keep only a primitive number.
Edge cases
  • Negative starts (e.g., `-2`) should count upward correctly.
  • Large numbers work until you hit `Number.MAX_SAFE_INTEGER` (then precision issues can appear).
  • Multiple counters created from separate calls must not interfere with each other.
Techniques
  • Leverage lexical scoping: inner function closes over `n`.
  • Prefer returning a function over exposing mutable objects to keep encapsulation tight.

Resources

  • MDN – Closures
  • You Don’t Know JS Yet – Scope & Closures (free book)

Similar questions

Once (Function Wrapper)easyCreate a Spy Function (Test Double)intermediateCurry Functionintermediate

Guides

Frontend interview preparation guideGuideFrontend coding interview questions and prep guideBlueprintJavaScript Problems That Actually Show UpBlueprintBuild Great UI in 60 MinutesBlueprint

Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.

Open frontend interview questionsBrowse JavaScript interview questionsOpen Essential 60Open Machine Coding HubOpen Frontend Coding ChallengesOpen System DesignOpen Interview Prep GuideOpen System Design BlueprintOpen Framework Prep PathsOpen Study PlansOpen JavaScript mastery study planOpen Company PrepOpen JavaScript Framework Prep Guide
↗Incidents hub
44 / 88Next →→