Closure (JavaScript)

A closure is a function that remembers the variables from the scope where it was created, even after that outer function has finished running.

JavaScript

Closures let an inner function keep access to an outer function's variables. This is the basis for data privacy and for functions that 'remember' state between calls.

Every time you create a function inside another function and return it, you create a closure.

Examples

JavaScript

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

Output:

1 2 3

Learn it in a lesson

See also

Back to the Dictionary