Closure

A JavaScript feature where an inner function has access to variables from its outer (enclosing) function, even after the outer function has returned.

Overview

Closures are created whenever a function is created in JavaScript. They allow a function to access variables from its parent scope, enabling data privacy, factory functions, and maintaining state in functional programming. Closures are fundamental to understanding JavaScript scope and are widely used in modern JavaScript development.

Example

javascript
function createCounter() {
  let count = 0; // Private variable

  return {
    increment() {
      count++;
      return count;
    },
    decrement() {
      count--;
      return count;
    },
    getCount() {
      return count;
    }
  };
}

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

Key Points

  • Inner functions remember their outer scope
  • Enables data privacy and encapsulation
  • Created every time a function is created
  • Common in callbacks and event handlers
  • Can lead to memory leaks if not managed properly

Learn More