Topic 15 of 37
Lexical Environment & Scope Chain
Overview
Scope determines the accessibility of variables. JavaScript uses Lexical Scoping, meaning that variable scope is determined by its position in the source code. A Lexical Environment consists of the local variables AND a reference to the outer (parent) Lexical Environment. When JS cannot find a variable in the current scope, it looks up the Scope Chain to the parent, and so on, until it reaches the Global scope.
Syntax
Scope lookup only goes UP the chain, never down. Inner functions have access to outer variables, but outer functions do not have access to inner variables.
The Scope Chain in Action
javascript
const globalVar = "I am global";
function outer() {
const outerVar = "I am outside";
function inner() {
const innerVar = "I am inside";
// inner can access all three!
console.log(innerVar, outerVar, globalVar);
}
inner();
// console.log(innerVar); // ReferenceError! Outer cannot access inner.
}
outer();Common Pitfalls
- Accidentally creating global variables by forgetting 'let', 'const', or 'var' inside a function (in non-strict mode).
Interview Tips
- Understand the difference between Lexical Scope (where the function was written) and Dynamic Scope (where the function was called). JavaScript is purely Lexical.
Real-World Example
Module encapsulation relies on lexical scoping. Variables defined in a file are not globally accessible unless explicitly exported.
example
javascript
// userHelper.js
const privateAPIKey = "12345"; // Hidden from other files
export function fetchUser() {
// Can use privateAPIKey due to lexical scoping
return fetch(`https://api.com/user?key=${privateAPIKey}`);
}