← Back to all Posts

Understanding JavaScript Closures

What is a Closure?

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.

Why Do They Matter?

Closures are one of the most powerful features in JavaScript. They allow you to:

  • Emulate private methods
  • Create function factories
  • Maintain state in an otherwise stateless environment

Practical Example

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

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

This pattern is used extensively in modern JavaScript development.