Skip to content
Exercise · Closures and this · lesson 8 of 11

Exercise: a counter

Write a function function makeCounter(start) that returns an object with two methods, next and reset. The call next() increases the count by 1 and returns the new value, and reset() sets the count back to start.

  • makeCounter(0), then next() → 1, one more next() → 2
  • makeCounter(5): next(), next(), reset(), then next() → 6
  • makeCounter(-3), then next() → -2

Constraints: start is an integer from -1000 to 1000; the result of reset() is not checked; every counter created by a separate call of makeCounter has its own count, and calls on one counter do not change another.

Do not add extra imports unless the task says so explicitly.

make-counter.js — javascript
javascript · 9 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way