← All concepts
A Closer Look at Functions

Closures

A function keeps access to the variables it was born in, even after that scope returns.

Loading visual…

Definition

A closure is a function together with references to the variables from the scope where it was created. When a function is returned from or passed out of its parent, it carries that surrounding state with it, so it can still read and update those variables long after the parent has finished running.

Examples

function makeCounter() {
  let count = 0;
  return () => ++count;
}
const next = makeCounter();
next(); // 1
next(); // 2

The returned arrow function keeps a live reference to count, so each call updates the same private variable.

Where you see this

Practice this

Further reading