What is a Closure?

Definition

A closure is a function together with the variables from the scope where it was created. The inner function "remembers" those variables even after the outer function has returned.

Example

function makeGreeter(greeting) {
  return function (name) {
    return greeting + ", " + name;   // uses greeting from the outer function
  };
}
const hello = makeGreeter("Hello");
const namaste = makeGreeter("Namaste");
console.log(hello("Asha"));
console.log(namaste("Vikram"));

Output

Hello, Asha
Namaste, Vikram

Each Call Gets Its Own Variables

Example

function counter() {
  let count = 0;
  return () => ++count;
}
const a = counter();
const b = counter();
console.log(a(), a(), a());
console.log(b());       // b has its own count

Output

1 2 3
1