Lexical Scope Explained - Scope Rules and Closure Example
Lexical scope means that the scope of a variable is determined by where it is written in the code, not where the function is executed.
What is Scope?
Scope defines:
- Where a variable is accessible
- Where it exists in the program
If a variable is not accessible somewhere, you may see:
undefined or ReferenceError
Definition 2:
A function can access:
- Its own variables
- Its parent function’s variables
- Global variables
This behavior is called Lexical Scope.
Basic Example
let a = 10;
function outer() {
let b = 20;
console.log(a, b);
function inner() {
let c = 30;
console.log(a, b, c);
}
inner();
}
outer();
Output:
10 20
10 20 30
Explanation
inner()can access:c(its own variable)b(parent variable)a(global variable)- But the reverse is NOT possible:
outer()cannot accessc- Global scope cannot access
borc
Important Rules of Lexical Scope
- Scope is decided by where the function is written, not where it is called
- JavaScript follows lexical (static) scoping
- Child functions can access parent and global variables
- Parent cannot access child variables
- This behavior enables closures
Example Showing Scope Limitation
let a = 10;
function outer() {
let b = 20;
console.log(a, b);
}
outer();
console.log(b); // Error: b is not defined
Lexical Scope + Closure Example
function greet(msg) {
return function (name) {
console.log(msg, name);
};
}
const sayHello = greet("Hello");
sayHello("Sidhu");
Output:
Hello Sidhu
Explanation
greet("Hello")executes first- It returns a function
- That returned function still remembers
msg - This is closure, enabled by lexical scope
Real Understanding
Lexical scope defines:
- How variables are accessed
Closure uses that behavior to:
- Remember variables even after execution
Why Lexical Scope is Important
Used in:
- Closures
- Callbacks
- Event handlers
- Functional programming
- Modular code design