JavaScriptClosures & Scope

Understanding Closures in JavaScript

A closure is the combination of a function bundled together 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.

Key Concepts

Lexical Scoping: JavaScript uses lexical scoping, which means that the scope of a variable is determined by its position in the source code.

function outerFunction(x) {
  // x is in scope here
  return function innerFunction(y) {
    // Both x and y are accessible here
    return x + y;
  };
}

const addFive = outerFunction(5); console.log(addFive(3)); // Output: 8

Practical Applications

  • Data Privacy: Closures allow you to create private variables that cannot be accessed from outside the function.
  • function createCounter() {
      let count = 0;
      return {
        increment: () => ++count,
        decrement: () => --count,
        getCount: () => count
      };
    }

    const counter = createCounter(); counter.increment(); // 1 counter.increment(); // 2 console.log(counter.getCount()); // 2 // count is not accessible directly

  • Function Factories: Create specialized functions from general ones.
  • function multiply(factor) {
      return (number) => number * factor;
    }

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

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

  • Event Handlers: Maintain state in async callbacks.
  • Common Pitfalls

    Be careful with closures in loops - use let instead of var to create a new binding for each iteration.