Sobes.tech
Junior

What is a closure in JavaScript?

sobes.tech AI

Answer from AI

This is a function that remembers and has access to its outer lexical environment even after that environment has finished execution.

Main concepts:

  • Lexical environment: Each function has access to variables declared in its own scope, as well as to variables in outer scopes where it was created.
  • Preserving state: Thanks to closures, inner functions can retain access to variables from outer functions, thus maintaining state.

Example:

function createCounter() {
  let count = 0; // External variable accessible to the inner closure

  return function() { // Closure
    count++; // Access to variable from outer scope
    return count;
  };
}

const counter1 = createCounter();
console.log(counter1()); // 1
console.log(counter1()); // 2

const counter2 = createCounter(); // Creates a new independent closure
console.log(counter2()); // 1

In this example, the inner anonymous function is a closure. It "remembers" the variable count from the outer function createCounter, even after createCounter has finished executing. Each new call to createCounter creates a new, independent closure with its own count value.

Applications:

  • Private variables and methods (Module pattern).
  • Memoization.
  • Factory functions.
  • Asynchronous operations (e.g., in callbacks).

Closures are a fundamental aspect of JavaScript and are widely used in functional programming and in building complex architectures.