Back to questions
JuniorTheoryCommon
What does the program print?
function makeCounter() {
let count = 0;
return () => {
count += 1;
return count;
};
}
const a = makeCounter();
const b = makeCounter();
console.log(a(), a(), b());1 2 1
- Expecting
1 2 3: each call ofmakeCountercreates its owncount, sobstarts from zero and does not see the count ofa. - Expecting
1 1 1:let count = 0runs once permakeCountercall, not on each call of the returned function, soakeeps counting up.
- What would
a()return if you called it a third time? - How could two counters share one
count?