Sikau

Advanced JavaScript · Day 1 · about 25 min

Closures

Functions that remember where they were born.

Functions with a backpack

In the foundations course you learned that a function can see variables around it. Here's the twist: it keeps seeing them even after the outer function has finished. That's a closure, and it powers counters, private data, event handlers and much of modern JavaScript.

A function that returns a function

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

const next = makeCounter();
console.log(next());
console.log(next());

const other = makeCounter();
console.log(other());

A backpack: When a function is created, it packs a backpack with the variables around it. Wherever it travels, it carries the backpack — and can read and change what's inside.

The rest of this lesson

  • Private dataexplain
  • Closures you already useexplain
  • Predict the outputpredict
  • Live link, not a copypredict
  • Your turnwrite code
  • Challengechallenge
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 27 lessons of Advanced JavaScript