The Closure Creation Moment
You'll learn: When exactly closures are created—at definition time, not when the function is called.
The Key Timing
A closure is formed the instant a function is defined, not later when you call it. At that exact moment of creation, JavaScript captures and "remembers" the entire lexical environment surrounding the function—every variable accessible at that point gets locked into the closure's memory.
This is crucial: the environment is "photographed" at definition time, like taking a snapshot of all variables in scope right then and there.
Why This Matters
Consider what happens when you define a function inside another function:
function makeCounter() {
let count = 0; // This exists when inner function is DEFINED
function increment() {
count++; // Closure was created above, capturing 'count'
return count;
}
return increment;
}
const counter = makeCounter(); // increment function is created NOW
The increment function forms its closure the moment line 4 runs—when makeCounter executes and defines increment. At that instant, count is captured. Even though makeCounter finishes and returns, increment keeps its reference to that specific count variable forever.
Definition vs Call Time
let message = "Hello";
function greet() {
console.log(message); // Captures whatever 'message' is at definition
}
message = "Goodbye";
greet(); // Prints "Goodbye" — closure holds reference, not value snapshot
The closure was created when greet was defined (when that message existed), but it holds a reference to the variable, not a frozen copy.
Key Takeaway: Closures are created at function definition time, capturing the lexical environment at that moment—not when you call the function later.