AniUI Academy
easy+150 XPPractice

Build a counter with private state

Before hooks, this was how every widget kept state: a factory function returns an object of methods, and the count itself lives in the factory's scope where no caller can reach it. It is still how you write a module that must not be poked at from the console.

Implement createCounter(start = 0). It returns an object with exactly four methods: increment() adds one and returns the new count, decrement() subtracts one and returns the new count, value() returns the current count without changing it, and reset() sets the count back to start and returns it. The count must not be exposed as a property on the returned object, so its only own enumerable properties are those four methods. Two counters created separately share nothing.

What it has to do

  • increment() and decrement() return the new count.
  • value() returns the current count without changing it.
  • reset() restores the original start value and returns it.
  • The returned object's only own enumerable properties are the four methods — the count stays private.
  • Separate counters keep independent state.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.