What is closure in JavaScript

· Category: JavaScript

Short answer

A closure is a function that retains access to its lexical scope even when executed outside that scope, enabling data encapsulation and stateful functions.

How it works

When a function is created, it captures references to variables in its surrounding scope. Even if the outer function returns, the inner function keeps those references alive.

Example

function makeCounter() {
  let count = 0;
  return {
    increment: () => ++count,
    decrement: () => --count,
    get: () => count
  };
}
const counter = makeCounter();
counter.increment();
console.log(counter.get()); // 1

Why it matters

Closures power module patterns, factory functions, and event handlers with preserved state. They are fundamental to avoiding global variables and creating private data in JavaScript before classes with private fields.