Skip to content

Latest commit

 

History

History
128 lines (93 loc) · 2.85 KB

File metadata and controls

128 lines (93 loc) · 2.85 KB

The Scope Chain, Scope & Lexical Environment

Scope in JavaScript

Definition: Scope is the current context of execution in which variables are accessible.

Types of Scope:

1. Global Scope

  • Variables accessible anywhere in the program.
  • Created in the Global Execution Context.
var x = 10; // global
function test() {
  console.log(x); // 10
}
test();

2. Function Scope (Local Scope)

  • Variables declared inside a function are accessible only within that function.
function demo() {
  var y = 20; // local
  console.log(y);
}
// console.log(y); // ReferenceError

3. Block Scope (ES6 let / const)

  • Variables declared inside {} are accessible only inside that block.
{
  let z = 30;
  console.log(z); // 30
}
// console.log(z); // ReferenceError

Lexical Environment

Definition: A Lexical Environment is a structure that stores variable and function declarations for a given execution context, along with a reference to its outer lexical environment.

Key Points:

  • Created at compile time (before execution).
  • "Lexical" means "by position in the source code".
  • Each function and block creates its own lexical environment.

Example:

function outer() {
  let a = 10;
  function inner() {
    let b = 20;
    console.log(a + b);
  }
  inner();
}
outer();

How it works:

  • inner is lexically inside outer.
  • inner's lexical environment:
    • Stores: b
    • Outer referenceouter's lexical environment (stores a).

Scope Chain

Definition: The Scope Chain is the chain of lexical environments used to resolve variable access.

How it works:

  1. JavaScript first looks for a variable in the current lexical environment.
  2. If not found, it follows the outer reference to the parent lexical environment.
  3. This continues until:
    • The variable is found, or
    • The global environment is reached (then ReferenceError if still not found).

Example:

let globalVar = 'global';

function outer() {
  let outerVar = 'outer';

  function inner() {
    let innerVar = 'inner';
    console.log(globalVar, outerVar, innerVar);
  }

  inner();
}
outer();

Lookup order when inner runs:

  1. inner → finds innerVar
  2. Goes to outer → finds outerVar
  3. Goes to global → finds globalVar

Diagram (Interview-Style)

[ Global Lexical Environment ]
   globalVar
        ↑
[ outer Lexical Environment ]
   outerVar
        ↑
[ inner Lexical Environment ]
   innerVar

Interview Soundbite

"A lexical environment is a record of variables and functions in a particular execution context, plus a reference to its outer lexical environment. Scope defines where a variable can be accessed, and the scope chain is the series of these lexical environments that JavaScript traverses when resolving identifiers."