In our previous lesson, we dissected the Execution Context and established that its core component for managing scope is the Lexical Environment, which contains an Environment Record (for local variables) and a crucial outer reference pointing to its parent's environment. We now have all the necessary components on the table.
This lesson puts those components into motion. We will focus on how the JavaScript engine uses the outer reference to resolve variables, a process that forms the very foundation of scope in JavaScript. You will learn to trace this "scope chain" step-by-step, moving from an intuitive understanding of scope to a precise, mechanical model. This skill is non-negotiable for diagnosing some of the most subtle bugs you'll encounter in production.
Core Concepts: The Scope Chain
[Always asked]
Let's begin with a simple piece of code. Before running it, predict what will be logged.
const user = 'Alex';
function logUser() {
const role = 'Admin';
function getDetails() {
const department = 'Engineering';
console.log(`${user} is an ${role} in the ${department} department.`);
}
getDetails();
}
logUser();
The code logs "Alex is an Admin in the Engineering department." The getDetails function has no local variables named user or role, yet it accesses them correctly. How?
The answer lies in the scope chain. In the last lesson, we identified the outer reference within a Lexical Environment. This reference isn't just a pointer; it's a link in a chain. When a function is created, its internal [[Environment]] property gets a reference to the Lexical Environment in which it was defined. This chain of Lexical Environments, linked by their outer references, is the scope chain.
Variable lookup is simply a traversal of this chain.
- When the engine needs to resolve an identifier (e.g.,
user), it first checks the Environment Record of the current running Execution Context's Lexical Environment. - If the identifier is not found, it follows the
outerreference to the parent Lexical Environment. - It then searches the parent's Environment Record.
- This process repeats, moving up the chain from one
outerreference to the next, until the identifier is found or the chain ends. - The chain ends at the Global Lexical Environment, whose
outerreference isnull. If the identifier is not found there, the engine throws aReferenceError.
The following video provides an excellent visual demonstration of this process.
The Scope Chain, 🔥Scope & Lexical Environment | Namaste JavaScript Ep. 7
Akshay Saini's "Namaste JavaScript" series offers one of the clearest visual explanations of the scope chain.
Watch the segment from this point. The presenter builds the call stack and illustrates how each function's Lexical Environment contains a reference to its parent's environment. Pay close attention to how he traces the search for a variable from the innermost function outward, level by level. This is the exact mental model you need to build.
Static (Lexical) Scoping vs. Dynamic Scoping
A critical feature of the scope chain is that it is lexical. This means the chain is determined by where functions and blocks are written in your source code, not by where they are called. This is also known as static scoping.
When the getDetails function was defined, it was physically sitting inside the logUser function. Therefore, its Lexical Environment's outer reference was permanently linked to the logUser Lexical Environment. The logUser function, in turn, was defined in the global scope, so its outer reference was linked to the Global Lexical Environment. The chain is fixed at definition time.
This diagram illustrates the search path for a variable in a nested scope, which is exactly how our example code works.

The alternative, which JavaScript does not use, is dynamic scoping. In a dynamically scoped language, the engine would search down the call stack, not up the lexical scope chain. This would make a function's behavior dependent on whatever function happened to call it, leading to highly unpredictable code.
Everything I Wish I Knew About Javascript Scoping A Week ...
Jesse Duffield's article, which we looked at previously, has a fantastic, concise section explaining this distinction.
Read the section titled Static vs Dynamic Scoping. Focus on the code example where inner() is called from outer(). The explanation of why inner accesses the global x instead of outer's x is the essence of lexical scope.
Visualizing the Scope Chain in DevTools
You don't have to imagine the scope chain; you can see it directly in your browser's developer tools. When you place a breakpoint inside a function, the "Scope" panel shows you the exact chain of environments the engine will traverse.
Let's see this in action. The same video from earlier demonstrates this clearly.
The Scope Chain, 🔥Scope & Lexical Environment | Namaste JavaScript Ep. 7
This final segment connects the theory to practice by showing the scope chain in Chrome DevTools.
Watch from this timestamp. Notice how the "Scope" panel lists the local scope first, followed by its parent's scope (often labeled as "Closure"), and finally the "Global" scope. This is a direct visualization of the Lexical Environment chain.
The term "Closure" in the debugger's scope panel refers to any scope that is "closed over" by an inner function. It's simply a parent's Lexical Environment that the current function retains access to. We will dive deep into closures in a later lesson. For now, just see it as the next link up in the scope chain.
Mental Model: The Russian Doll of Dictionaries
Imagine your nested functions are like a set of Russian dolls. Each doll contains a small dictionary (its Environment Record).
When you need to look up a variable (a word), you first check the dictionary in the smallest, innermost doll you're currently in.
- If you find the word, your search is over.
- If you don't, you open that doll to reveal the next larger doll that contains it. You then check the dictionary of that doll.
This process continues—opening dolls to get to the next outer one—until you find the word or you've opened the largest, outermost doll (the Global scope). The outer reference is the act of opening a doll to access its parent. Because the dolls are nested physically, the chain of command is fixed. You can't change which doll is inside another. This is lexical scope.

Common Misconceptions
-
Myth: "The scope chain follows the call stack."
- Reality: This describes dynamic scoping. JavaScript's scope chain is lexical, determined by where functions are written in the source code, not the order in which they are called. A function's parent scope is permanent, regardless of its caller.
-
Myth: "If a variable isn't found, its value is
undefined."- Reality: If the engine traverses the entire scope chain to the end (
outer: null) and does not find the identifier, it throws aReferenceError. The valueundefinedis what's assigned to variables that have been declared but not yet initialized (a topic for our next lesson). An undeclared variable doesn't exist in any Environment Record in the chain.
- Reality: If the engine traverses the entire scope chain to the end (
-
Myth: "Block scope (
{...}) works differently from function scope for lookups."- Reality: The mechanism is identical. An
ifblock, aforloop, or even a standalone{}block creates its own Lexical Environment. Itsouterreference points to the surrounding environment (either a function or the global scope). When resolving a variable inside a block, the engine starts there and walks up the chain just as it would from a function.
- Reality: The mechanism is identical. An
Senior Insight
A mid-level developer knows that an inner function can access variables from an outer function. A senior engineer understands this is a deterministic traversal of a linked-list-like data structure (LexicalEnvironment) via outer pointers. This mechanical model allows them to reason about edge cases a mid-level developer might miss. For instance, when analyzing performance, they understand that variable access is not free—a deeply nested function accessing a global variable incurs a lookup cost for each link in the scope chain. While modern JS engines are highly optimized, in extremely hot code paths (like a rendering loop or data processing function running thousands of times per second), minimizing scope chain lookups by caching a variable locally can be a valid micro-optimization. They see scope not as a rule, but as a physical structure with performance characteristics.
Production War Story
A team was developing a complex analytics dashboard. They had a utility module, formatters.js, with a globally-used function formatCurrency(value). Inside formatters.js, at the top level, a configuration object was defined: const config = { currencySymbol: '$' };. The formatCurrency function used this config object to work.
// formatters.js
const config = { currencySymbol: '$' };
export function formatCurrency(value) {
// ... logic ...
return `${config.currencySymbol}${value.toFixed(2)}`;
}
A new feature required displaying prices in Euros for a specific component. A developer working on that component created a local config object:
// EuroDisplayComponent.js
import { formatCurrency } from './formatters.js';
const config = { currencySymbol: '€' }; // Local config
function renderPrice(price) {
const localPrice = 200;
// Developer expects this to use the local '€' config
console.log(formatCurrency(localPrice));
}
renderPrice(); // Outputs "$200.00", not "€200.00"
The developer was surprised when the output was still in dollars. They assumed that because formatCurrency was called from within a scope that had a local config object, it would use that one. But lexical scoping dictates that formatCurrency's scope chain was fixed when it was defined in formatters.js. Its outer environment is the global scope of that module, where config.currencySymbol is '$'. The local config in EuroDisplayComponent.js was never part of formatCurrency's scope chain, so it was never found during the lookup. The bug caused incorrect currency symbols to be shown to European users until it was caught. The fix involved modifying formatCurrency to accept the configuration as an argument, making its dependencies explicit rather than relying on a "magical" lexical lookup.
Conclusion
You have now traced the exact path the JavaScript engine takes to find variables. The seemingly magical ability of nested functions to access outer variables is, in reality, a simple and predictable traversal of the scope chain.
Key Takeaways:
- The scope chain is a linked list of Lexical Environments, connected by
outerreferences. - Variable resolution is a search that starts at the current Lexical Environment and moves up the chain until the variable is found or the chain ends.
- JavaScript uses lexical (static) scoping: the scope chain is determined by how the code is written, not how it is executed.
- If a variable is not found anywhere in the scope chain, a
ReferenceErroris thrown.
In the next lesson, we will zoom in on a single Lexical Environment and examine what happens during its creation phase, specifically the often-misunderstood behaviors of hoisting and the "Temporal Dead Zone" for let and const.