Closures

A function returned from another keeps the variables it was created with. Two counters each keep their own count.

JavaScript · beginner · 8 min · 24 steps · free

What you'll learn

Closures.js

function makeCounter() {
  let count = 0;
  return function increment() {
    count = count + 1;
    return count;
  };
}

const counterA = makeCounter();
const counterB = makeCounter();
counterA();
counterA();
console.log(counterA(), counterB());

Step by step

  1. Before the first line runs, JavaScript reads the whole file: the function makeCounter already exists. This is called hoisting.
  2. JavaScript calls makeCounter(). It gets its own variables.
  3. count is a local variable of this call of makeCounter.
  4. makeCounter returns the inner function increment. increment uses count, so count must outlive this call.
  5. makeCounter has returned, yet its count lives on, reachable only through counterA.
  6. A second call of makeCounter: a brand-new count, and a brand-new increment around it.
  7. count is created with the value 0.
  8. makeCounter returns the function increment().
  9. makeCounter() has finished, so its variables are gone. The value it returned, function increment(), is stored in counterB.
  10. counterA() runs increment. It can still use count from the first makeCounter call.
  11. count changes from 0 to 1.
  12. increment returns 1.
  13. increment() has finished, so its variables are gone.
  14. JavaScript calls increment(). It gets its own variables. It can still use count from makeCounter() #1, which has already returned: the closure keeps it alive.
  15. count changes from 1 to 2.
  16. increment returns 2.
  17. increment() has finished, so its variables are gone.
  18. JavaScript calls increment(). It gets its own variables. It can still use count from makeCounter() #1, which has already returned: the closure keeps it alive.
  19. count changes from 2 to 3.
  20. increment returns 3.
  21. JavaScript calls increment(). It can still use count from makeCounter() #2, which has already returned: the closure keeps it alive.
  22. counterB's own count goes from 0 to 1. counterA's count stays 3.
  23. increment returns 1.
  24. Printed: 3 and 1. Two closures, two separate counts.

Common mistakes

Best practices

Key takeaways

Check yourself

Can code outside read count directly?

Answer: No, only increment can. That is how closures make private state.

Two calls of makeCounter share count?

Answer: No

·

More in Functions