JavaScript Quirks

Closure Counter

mediumjs-quirksclosure
0:00

Problem

Implement `createCounter()` that returns an object with three methods: `increment()`, `decrement()`, and `value()`. The counter should start at 0 and persist state across calls via a closure. Each call to `createCounter()` must return an independent counter.

Your solution
Test results
Click Run tests to check your solution against the test cases.

About this challenge

Closure Counter is a medium javascript quirks coding challenge. It explores a surprising corner of JavaScript's behavior — the kind of gotcha that causes real bugs. Write your solution in the editor above, run it against the test cases, and get instant feedback — free, in your browser, no sign-up.

Show a hint & approach (spoiler)

Hint: Declare a `count` variable in the outer function. Return an object whose methods close over that variable.

Approach: Closures capture variables from their lexical scope. Returning inner functions that reference a local variable keeps that variable alive and private.

Keep practicing

Browse all coding challenges, or build intuition for the underlying concepts with the algorithm visualizers and the developer cheatsheets.