JavaScript · Junior · Question 18 of 75

What does this code print?

function makeCounter() {
  let count = 0;
  return () => ++count;
}
const c = makeCounter();
c(); c();
console.log(c());

Explanation

This is a closure: the returned function remembers the count variable from the scope where it was created, and each call increments it. Calling makeCounter() again would create an independent counter.

Further reading

Problem with a question

JavaScript · Junior · question 18

Test yourself

Take the JavaScript · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz