Hello! Let's dive into our next lesson.
In our previous session, we explored how JavaScript's execution context and hoisting work. We saw that when a function finishes running, its execution context is popped off the call stack and its local variables are typically destroyed. But what if we wanted a function to remember the variables from the scope where it was created, even long after that scope has closed?
This lesson answers that question by introducing one of the most powerful and foundational concepts in JavaScript: closures. Understanding closures is a significant step toward mastering JavaScript, as they are crucial for advanced patterns you'll encounter when learning Next.js and TypeScript. Your preference for understanding the "why" behind the code will be particularly helpful here, as we'll go deep into the mechanics of how closures work.
By the end of this lesson, you will be able to define a closure and explain how it provides access to an outer function's scope even after the outer function has returned.
The Core Idea: Functions with Memory
At its heart, a closure is a function that has "memory". It remembers the environment—the scope—in which it was created.
Consider this classic example:
function createCounter() {
let count = 0; // This variable is local to createCounter
// This inner function is returned
function increment() {
count++;
console.log(count);
}
return increment;
}
// 1. Call createCounter. It runs, and returns the 'increment' function.
const counter1 = createCounter();
// 2. The createCounter() function has finished. Its execution context is gone.
// So, how does counter1 still have access to the 'count' variable?
counter1(); // logs: 1
counter1(); // logs: 2
counter1(); // logs: 3
This is the magic of closures. The counter1 function, even though it's being called in the global scope, "remembers" the count variable from the createCounter scope where it was born. Let's find out how.
How Closures Work: A Look Under the Hood
To understand closures, we need to build upon our knowledge of the Execution Context and Call Stack. This is a perfect opportunity to see these concepts in action to create a powerful feature.
The video below provides an excellent step-by-step visualization of exactly what happens in the JavaScript engine. It picks up right where we left off with Execution Contexts.
Master JavaScript Execution Context — Hoisting, Scope & Closures Made Clear
Watch this segment from 'Master JavaScript Execution Context' by logicBase Labs. It will walk you through the entire process, showing how a closure is created and used.
Watch from 42:25 to 46:03. Pay close attention to how the video illustrates these steps: The doSum function is called and its execution context is created. It returns an anonymous inner function. The doSum execution context is popped from the stack, but its lexical environment is preserved in a 'closure scope'. When the inner function is later called, it uses this preserved scope to find the variables it needs.
To summarize the key points from the video:
- Creation: When an inner function is created, JavaScript gives it a hidden property that links to the lexical environment of its parent function. The lexical environment is essentially an object that holds all the local variables of that function's scope.
- Return: The parent function executes and returns the inner function. Normally, the parent function's execution context would be popped from the call stack and its memory (including its lexical environment) would be marked for garbage collection.
- Preservation: However, the JavaScript engine recognizes that the inner function (which is still alive) has a link to its parent's lexical environment. Because this link exists, the parent's environment is not garbage collected. It is kept in memory.
- Execution: Later, when you call the inner function, it creates its own execution context. If it needs a variable that isn't in its own local scope, it follows the link back to its remembered parent environment to find it.
This combination of the inner function and its "remembered" parent environment is the closure.

Lexical Environment: The Technical Detail
The term "lexical environment" is key. "Lexical" refers to the fact that scope is determined by where you write your code, not where you call it. An inner function is lexically nested inside an outer function, so it gets access to that outer scope.
The javascript.info website has one of the best technical explanations of this concept.
To solidify your deep understanding, let's read a more formal explanation from the article 'Variable scope, closure'. This will introduce the technical terms for the concepts we've seen visually.
Read the sections titled 'Lexical Environment', 'Step 3. Inner and outer Lexical Environment', and 'Step 4. Returning a function'. This will take you through the formal definition and show you how all functions in JavaScript are technically closures because they all have this hidden [[Environment]] property that links to their creation scope.
The most important takeaway from that reading is: A closure is a function that remembers its outer variables and can access them. In JavaScript, all functions are naturally closures. The most powerful examples are when a function is returned from another function, preserving a scope that would have otherwise been destroyed.
Test your understanding!
The createCounter function from our first example is called twice, creating two different counters. What will the following code log to the console? Why?
const counterA = createCounter();
const counterB = createCounter();
counterA(); // What is logged?
counterA(); // What is logged?
counterB(); // What is logged?
Show answer
The output will be:
1(fromcounterA())2(fromcounterA())1(fromcounterB())
Explanation:
Each time createCounter() is called, a new execution context and a new lexical environment are created. This means a new, separate count variable is created each time.
counterAis a closure that "remembers" the firstcountvariable.counterBis a completely independent closure that "remembers" the secondcountvariable.
They do not share the same state. This demonstrates that closures encapsulate the state of a specific function call.
Closures Remember References, Not Values
One final, crucial detail: a closure doesn't take a "snapshot" of the variables' values at the time it was created. Instead, it holds a reference to the variables themselves. This means if the variable's value changes, the closure will see the updated value.
This is especially important in asynchronous code, like with setTimeout.
How Closures Work in JavaScript: A Handbook for ...
The concept of 'references vs. values' can be tricky. This segment from a freeCodeCamp handbook on closures explains and demonstrates it perfectly.
Watch this section from 5:48 to 8:37 (the section titled 'Closures in Asynchronous Code'). The video shows an example with setTimeout where a global variable is changed after the timeout is set but before the callback function runs. The final output proves that the closure accesses the most recent value of the variable via its reference.
This behavior is exactly why closures are so fundamental to handling events and asynchronous operations in JavaScript—the callback function can reliably access variables from its surrounding scope, no matter when it eventually executes.
Conclusion
You've just unpacked one of JavaScript's most essential concepts. By linking closures back to the execution context and lexical environment, you now have a robust mental model for how functions can appear to have "memory."
Key Takeaways:
- A closure is the combination of a function and the lexical environment within which that function was declared.
- This "bond" allows an inner function to access variables from its outer (parent) scope, even after the parent function has finished executing.
- This works because the inner function maintains a reference to its parent's environment, preventing it from being garbage collected.
- When a closure is called, it searches for variables first in its own scope, and then in the "remembered" outer scopes via the scope chain.
- Each call to a function that creates a closure produces a new, independent closure with its own private environment.
Next Up:
Now that we've established what a closure is and how it works, our next lesson will focus on the why. We'll explore powerful practical applications of closures, such as creating private variables and encapsulating state. This is a common pattern for building organized and reusable code—a skill that is directly applicable to creating components in frameworks like Next.js.