Back to course

Understanding Closures (The Fundamentals)

JavaScript: The Complete '0 to Hero' Beginner Course

50. Understanding Closures (The Fundamentals)

A closure is a crucial and often misunderstood concept. A closure is created when an inner function is defined inside an outer function, and the inner function remembers and can access variables from its outer (lexical) scope, even after the outer function has finished executing.

Example: Creating a Counter

javascript function createCounter() { let count = 0; // This is the enclosed variable

return function() { // The inner function (the closure)
    count++; // Accesses the outer scope's 'count'
    return count;
};

}

// We call the outer function once. It returns the inner function. const counter1 = createCounter(); const counter2 = createCounter();

console.log(counter1()); // Output: 1 console.log(counter1()); // Output: 2 (It remembers its scope!)

console.log(counter2()); // Output: 1 (This is a completely separate scope)

Why are Closures Useful?

  1. Private Variables: They allow functions to have 'private' data that can only be accessed or modified via the returned inner function.
  2. State Persistence: They allow data to persist between function calls, essential for advanced programming patterns and React hooks.