Scriptdrill

Level 5: Async and functions Exercise 61 of 76 Free

A counter with private state

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

Return a counter object with three methods. `next()` returns the current value and then moves the counter on by `step`. `peek()` returns the current value without changing it. `reset()` puts the counter back to `start`. So `makeCounter()` gives 0, 1, 2 on successive `next()` calls. `step` can be negative or 0. Every counter is independent of the others.

What this exercise teaches

The methods are closures: they keep access to the variables of the makeCounter call that created them, and nothing outside can reach those variables. Each call to makeCounter creates a fresh set of variables, which is why two counters do not disturb each other.

A hint if you get stuck

Keep the current value in a variable inside `makeCounter` and return an object whose methods read and change that variable. Use default parameters for `start` and `step` rather than `||`, which would replace a step of 0.

Try it now, free, no account needed

Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.

Open this exercise

More exercises in Async and functions