Skip to main content

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

javascript
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:

LevelWhat is availableWhere it looks for variables
inner()c = 30First looks for c -> found
outer()b = 20Looks for b -> found
globala = 10Looks for a -> found

The chain looks like this:

javascript
inner -> outer -> global

If we wrote console.log(d), the search would go through the whole chain and end in an error:

javascript
ReferenceError: d is not defined

Example 2: a closure

javascript
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:

javascript
inner -> outer -> global

This 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

javascript
let x = 1; function foo() { let x = 2; function bar() { let x = 3; console.log(x); } bar(); } foo();

Output:

javascript
3

Why:

  • JS looks for x in the current bar context -> finds x = 3.
  • It does not go further along the chain (foo, global), because it already found a match.

Summary

TermDescription
ScopeThe set of variables accessible in a specific part of the code
Lexical EnvironmentThe internal object that holds variables and a reference to the outer environment
Scope ChainThe chain of all lexical environments the engine searches through for variables

Visually

javascript
[ 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.