Skip to curriculum
Jump to the editor

6.1. A counter with private state

Easy
Topics

This question is in

6. Functions and closures
5–10 min

A page shows "Item 1", "Item 2", "Item 3" as you add rows, and every new row needs the next id. A plain global variable works until a second list on the same page shares it, or some other script sets it back to 0. A closure gives each counter its own count that no other code can reach.

Write makeCounter(start) in counter.js. It returns a function. The first call of that function returns start, and every call after it returns one more than the call before.

Signature

JAVASCRIPT
function makeCounter(start) // returns a function
  • start: the first value the counter returns. A missing start (or undefined) counts as 0.
  • The returned function takes no arguments (any it gets are ignored) and returns a number.

Requirements

  1. makeCounter returns a function.
  2. The first call returns start (or 0 when start is missing), and each later call returns one more than the last.
  3. Any number works as start: negative numbers and fractions too.
  4. Each counter has its own count: counters made by separate calls to makeCounter never affect each other, even with the same start.
  5. Arguments passed to the counter are ignored.
  6. The count is private: it is not a property of the counter, not a global variable, and setting a property on the counter does not change it.

Examples

JAVASCRIPT
const next = makeCounter();
next(); // 0
next(); // 1
next(); // 2
JAVASCRIPT
const fromTen = makeCounter(10);
const fromMinusOne = makeCounter(-1);
fromTen();      // 10
fromMinusOne(); // -1
fromMinusOne(); // 0
fromTen();      // 11
JAVASCRIPT
const next = makeCounter(5);
next.count = 100; // a new property, not the count
next();           // 5
next(42);         // 6: the argument is ignored

Environment

  • Plain JavaScript in a browser page; the tests call the global makeCounter from counter.js.
  • start is always a number or missing; other types are out of scope.
  • Do not keep the count in a global variable or on the function object.

Hints

  1. A variable declared inside makeCounter is created again on every call to makeCounter. Who can still see it after makeCounter returns?
  2. Should the counter return the value before or after adding one?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…