Definition: Scope is the current context of execution in which variables are accessible.
- Variables accessible anywhere in the program.
- Created in the Global Execution Context.
var x = 10; // global
function test() {
console.log(x); // 10
}
test();- Variables declared inside a function are accessible only within that function.
function demo() {
var y = 20; // local
console.log(y);
}
// console.log(y); // ReferenceError- Variables declared inside
{}are accessible only inside that block.
{
let z = 30;
console.log(z); // 30
}
// console.log(z); // ReferenceErrorDefinition: 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.
- 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();inneris lexically insideouter.inner's lexical environment:- Stores:
b - Outer reference →
outer's lexical environment (storesa).
- Stores:
Definition: The Scope Chain is the chain of lexical environments used to resolve variable access.
- JavaScript first looks for a variable in the current lexical environment.
- If not found, it follows the outer reference to the parent lexical environment.
- 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();inner→ findsinnerVar- Goes to
outer→ findsouterVar - Goes to
global→ findsglobalVar
[ Global Lexical Environment ]
globalVar
↑
[ outer Lexical Environment ]
outerVar
↑
[ inner Lexical Environment ]
innerVar
"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."