Hack Frontend Community

Lexical Environment in JavaScript

What is Lexical Environment?

Lexical Environment is an internal structure used by JavaScript engine to store variables declared in a specific scope, and to determine where and how these variables can be used.

Each function, block {}, and global scope creates its own lexical environment during execution.


Lexical Environment Composition

Lexical environment consists of two parts:

  1. Environment Record
    • Stores all local variables, functions, parameters.
  2. Reference to outer lexical environment (outer)
    • Points to outer environment where function was created (not called!).

Example

function outer() {
  let a = 1;

  function inner() {
    let b = 2;
    console.log(a + b);
  }

  inner();
}

outer();
  • When outer is called, Lexical Environment for outer is created with variable a.
  • When inner is called, Lexical Environment for inner is created with variable b, and it has access to a through closure.

Environment Chain Visualization

Lexical ≠ Dynamic

JavaScript uses lexical scoping, which means:

Variables are accessible depending on where they're defined in code, not where they're called.

let x = 10;

function log() {
  console.log(x);
}

function run() {
  let x = 20;
  log(); // ❗ Will output 10, not 20!
}

run();

log() remembers context of its definition, not its call

Important:

Lexical environment is created when function runs and lives as long as there are references to it (e.g., through closures).

Summary

  • Lexical environment is a mechanism for storing variables in specific scope.
  • Each function, block or global scope has its own environment.
  • It forms a scope chain, which is how scope and closures work.
  • Understanding Lexical Environment helps understand how JavaScript finds and manages variables during execution.