B
BlogSmoke
Closures

Understanding JavaScript Closures

javascriptclosures

Understanding JavaScript Closures

A closure is a function that retains access to variables from its outer (enclosing) scope even after the outer function has returned.

Example

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

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

Use Cases

  • Data privacy / encapsulation
  • Factory functions
  • Event handlers and callbacks