Closures in javascript

A closure is a function that retains access to its outer scope's variables even after the outer function has returned. Closures are fundamental to JavaScript and enable patterns like data privacy, function factories, and callbacks.

Example

function createCounter() {
  let count = 0;
  return {
    increment: () => ++count,
    getCount: () => count,
  };
}

const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2

The inner functions close over 'count', keeping it private while providing controlled access.