Command Palette

Search for a command to run...

Hectal
Phase 3: Functions
JavaScript · Exercise 4 of 6 PreviousNext
Intermediate

A counter with private state

Write makeCounter(start = 0) that returns an object with four methods: increment(), decrement(), reset() (back to the start value) and value() (returns the current count).

Keep the count private in a closure: it must not be a property of the returned object. The count must never go below 0.

Then create one counter and wire the three buttons so the number on the page always shows the current count.

What Check tests

  1. Two counters keep separate counts
  2. reset() goes back to the start value
  3. The count never goes below 0
  4. The count is private (changing a property doesn't affect it)
  5. The + and − buttons update the number on the page
  6. The Reset button sets the page back to 0

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

Runs in your browser. Your code is saved here.

Your page

Press Run to see the page.

Console

Nothing logged yet.