Scope chain (chain of scopes)
What a Scope Chain is
A scope chain is the mechanism JavaScript uses to find variables. When code refers to a variable, the engine looks for it in the current scope, and if it is not found, goes "up the chain", to the parent scopes.
Put simply:
A scope chain is a chain of references to outer lexical environments, through which the engine searches for variables.
How it works
Every function in JS creates its own Lexical Environment. And that environment stores a reference to the outer environment, that is, to the place where the function was declared, not where it was called.
These references are exactly what form the scope chain.
Example 1: a simple chain
let a = 10;
function outer() {
let b = 20;
function inner() {
let c = 30;
console.log(a, b, c);
}
inner();
}
outer();What happens when inner() is called:
| Level | What is available | Where it looks for variables |
|---|---|---|
| inner() | c = 30 | First looks for c -> found |
| outer() | b = 20 | Looks for b -> found |
| global | a = 10 | Looks for a -> found |
The chain looks like this:
inner -> outer -> globalIf we wrote console.log(d), the search would go through the whole chain and end in an error:
ReferenceError: d is not definedExample 2: a closure
function outer() {
const outerVar = 'outside';
return function inner() {
console.log(outerVar);
};
}
const fn = outer();
fn();Here, the inner function remembered a reference to its outer environment outer, and that is also part of the scope chain.
The chain:
inner -> outer -> globalThis is what makes closures work: an inner function gets access to the outer function's variables, even after the outer one has finished running.
Example 3: variables with the same name
let x = 1;
function foo() {
let x = 2;
function bar() {
let x = 3;
console.log(x);
}
bar();
}
foo();Output:
3Why:
- JS looks for
xin the currentbarcontext -> findsx = 3. - It does not go further along the chain (
foo,global), because it already found a match.
Summary
| Term | Description |
|---|---|
| Scope | The set of variables accessible in a specific part of the code |
| Lexical Environment | The internal object that holds variables and a reference to the outer environment |
| Scope Chain | The chain of all lexical environments the engine searches through for variables |
Visually
[ Global Scope ]
^
[ outer() Scope ]
^
[ inner() Scope ]If inner cannot find a variable, it goes up the arrow until it finds it or reaches the global context.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.