×

javascript · level 3 · unit 1 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A is a function that carries its scope with it.

A function can be made inside another function and handed back with return. Here makeCounter builds a small function and returns it. A function that makes and returns new things like this is called a .

When makeCounter finishes, you might expect count to vanish. It survives, because the inner function still uses it. A function plus the variables it remembers is a closure, like a snail carrying its house wherever it goes.

Each call to the factory makes a fresh count, so two counters never share one.

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

() => { } is an arrow function: a short way to write a function with no name of its own.