Loading...
Loading...
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 consists of two parts:
function outer() {
let a = 1;
function inner() {
let b = 2;
console.log(a + b);
}
inner();
}
outer();
outer is called, Lexical Environment for outer is created with variable a.inner is called, Lexical Environment for inner is created with variable b, and it has access to a through closure.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).