Course contentsShow
← JavaScript
Lesson 500 of 2,72313. ClosuresFree lesson

Each Call Creates a New Closure

Each invocation of an outer function creates a fresh set of variables that inner functions will close over independently.

Each Call Creates a New Closure

You'll learn: How every separate invocation of an outer function produces its own independent closure environment.

When you call a function that returns an inner function, JavaScript creates a brand new closure each time. This means each invocation gets its own private set of variables that the returned inner function closes over—completely separate from other calls.

Think of it like ordering a takeout meal: each time you place an order, the restaurant gives you a fresh container with your food. One container doesn't share contents with another, even though they came from the same restaurant.

The Mechanism

When you call an outer function:

  1. JavaScript creates a new execution context
  2. New variables are allocated in memory
  3. The inner function "remembers" those specific variables
  4. Each subsequent call repeats this process with fresh variables
function createCounter() {
  let count = 0;
  return function() {
    count++;
    return count;
  };
}

const counter1 = createCounter(); // First closure created
const counter2 = createCounter(); // Second closure created

console.log(counter1()); // 1
console.log(counter1()); // 2
console.log(counter2()); // 1 (independent count variable!)
console.log(counter1()); // 3
console.log(counter2()); // 2

counter1 and counter2 each have their own count variable. They don't interfere with each other because each call to createCounter() created a separate closure with its own lexical environment.

Why This Matters

This independence lets you create multiple instances of the same behavior without conflicts—like having multiple timers, event handlers, or configuration wrappers that don't step on each other's toes.

Key Takeaway: Every invocation of an outer function spawns a new, isolated closure—giving each returned inner function its own private variable environment.