Skip to main content

What is a Closure?

Answer

A closure is a function that remembers variables from its outer scope even after the outer function has finished executing.

Example

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

const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2

How it Works

Use Cases

  • Data privacy
  • Function factories
  • Event handlers with state