What is a Closure in JavaScript?

Chief Editor
3 Min Read

A closure in JavaScript is a function that remembers the variables from its outer lexical scope even after the outer function has finished executing.

In other words:

  • A closure gives a function access to an outer function’s variables, even after the outer function has executed.
  • The function “closes over” the variables from its outer scope.

Key Characteristics of Closures:

  • Closures remember the environment in which they were created.
  • Closures can access variables from their outer scope even after the outer function is done executing.
  • Closures are created every time a function is created inside another function.

Example 1: Basic Closure Example

javascriptCopyEditfunction outer() {
    let count = 0; // Variable in outer scope

    function inner() {
        count++; // Accessing outer scope variable
        console.log(count);
    }

    return inner;
}

const counter = outer(); // outer() is executed, but its scope is preserved
counter(); // 1
counter(); // 2
counter(); // 3

Explanation:

  • outer() creates the variable count.
  • inner() is defined inside outer() and has access to count.
  • Even though outer() is done executing, the counter function still remembers count because of closure.
  • Each time counter() is called, it remembers the previous state of count.

Example 2: Closure with Parameters

javascriptCopyEditfunction multiplier(factor) {
    return function (number) {
        return number * factor;
    };
}

const double = multiplier(2);
const triple = multiplier(3);

console.log(double(5)); // 10
console.log(triple(5)); // 15

Explanation:

  • multiplier() returns a function that multiplies by factor.
  • The returned function remembers factor due to closure, even after multiplier() has finished execution.

Why Are Closures Useful?

  • Data privacy: Variables in closures are not accessible from outside.
  • Stateful functions: Functions can remember state between calls.
  • Callbacks and Event Handlers: Closures are common in asynchronous programming and event handling.

Common Use Cases of Closures:

Use CaseExample
Data hiding/encapsulationCounter, private variables
Factory functionsGenerating customized functions
Callbacks and async functionsEvent listeners, setTimeout
Function curryingPartial application of functions

Key Takeaways:

  • A closure is a function + the environment in which it was created.
  • Closures allow functions to remember and access their outer scope variables even after the outer function has completed.
  • Used heavily in JavaScript patterns like module pattern, callbacks, and functional programming.
Share This Article
Leave a Comment