Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
6.1. A counter with private state
Easy
Topics
This question is in
6. Functions and closuresA 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
function makeCounter(start) // returns a functionstart: the first value the counter returns. A missingstart(orundefined) counts as0.- The returned function takes no arguments (any it gets are ignored) and returns a number.
Requirements
makeCounterreturns a function.- The first call returns
start(or0whenstartis missing), and each later call returns one more than the last. - Any number works as
start: negative numbers and fractions too. - Each counter has its own count: counters made by separate calls to
makeCounternever affect each other, even with the samestart. - Arguments passed to the counter are ignored.
- 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
const next = makeCounter();
next(); // 0
next(); // 1
next(); // 2const fromTen = makeCounter(10);
const fromMinusOne = makeCounter(-1);
fromTen(); // 10
fromMinusOne(); // -1
fromMinusOne(); // 0
fromTen(); // 11const next = makeCounter(5);
next.count = 100; // a new property, not the count
next(); // 5
next(42); // 6: the argument is ignoredEnvironment
- Plain JavaScript in a browser page; the tests call the global
makeCounterfromcounter.js. startis 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
- A variable declared inside
makeCounteris created again on every call tomakeCounter. Who can still see it aftermakeCounterreturns? - 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…