JavaScript · Middle · Question 70 of 75

How can a function keep private state without classes?

function createCounter() {
  let count = 0;
  return { inc: () => ++count, get: () => count };
}

Explanation

This factory/closure pattern predates #private fields and is still common in composables and hooks.

Further reading

Problem with a question

JavaScript · Middle · question 70

Test yourself

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

Take this quiz