Closures

February 5, 2025
javascript

A closure is a fundamental JavaScript concept where a function retains access to variables from its outer scope even after the outer function has finished executing. In simpler terms, it's like a function remembering the environment it was created in.

Example

function createCounter() {
      let count = 0;  // This variable is "enclosed" in the closure
        return {
          increment: function() {
            count++;
            return count;
          },
          getCount: function() {
            return count;
          }
        };
      }
const counter = createCounter();

console.log(counter.getCount());  // Output: 0
console.log(counter.increment()); // Output: 1
console.log(counter.increment()); // Output: 2

Why are Closures useful?

  • Data privacy: Variables inside closures are not accessible from outside
  • State management: Maintain state without using global variables
  • Factory functions: Create functions with "built-in" data
  • Module pattern: Create private methods and properties

Common Use Cases

Closures are commonly used in:

  • Event handlers
  • Callback functions
  • Partial application and currying
  • Module patterns