Question 42

Question

Can you explain how closures work in JavaScript?

Answer

Imagine a function nested inside another function. The inner function has access to the variables in its surrounding scope (the outer function), even after the outer function has finished executing. This "memory" of the outer scope is what makes closures work.

Key Points:

  1. Lexical Scope: JavaScript uses lexical scoping, meaning that functions look for their variables within the surrounding code where they are defined, not just where they are called.

  2. Closure's Memory: When an inner function is created (even if it's never immediately called), it "remembers" and has access to all the variables from its parent scope—the closure.

Example:

function outerFunction(x) { 
  let y = 10; // Variable in outer function's scope

  function innerFunction() {
    console.log(x + y); // Accesses 'x' and 'y' from outer scope
  }

  return innerFunction; 
}

const myClosure = outerFunction(5); // Call outerFunction, creating the closure
myClosure(); // Outputs: 15 (accessing x=5 and y=10) 

Explanation:

  • outerFunction takes x as an argument. It defines y.

  • innerFunction is defined inside outerFunction, so it has access to both x and y.

  • When we call outerFunction(5), it returns innerFunction. Now, myClosure holds a reference to this inner function, which remembers the values of x (which is 5) and y (which is 10).

  • When we call myClosure(), even though outerFunction has finished executing, the closure still allows innerFunction to access those variables from its outer scope.

Why Closures Matter:

  • Data Encapsulation: They help create private variables within functions, preventing accidental modification from outside.

  • State Preservation: Closures can maintain state between function calls, useful for creating counters, timers, or other dynamic behavior.

  • Currying and Partial Application: Powerful techniques for building flexible and reusable functions.

Last updated