What is lexical scope in JavaScript?
Lexical scope means a function's accessible variables are decided by where it is written in the source code, not by where it is called. Inner code can see outer variables, never the reverse.
Explain it simply
Picture a college campus with nested boundaries: the hostel room is inside the hostel, which is inside the campus. From your room you can see the hostel notice board and the campus gate, but a visitor at the gate cannot see inside your room.
JavaScript scopes work the same way. A function can use variables from its own body and from every function or block that physically surrounds it in the code. This is decided when you write the code (lexically), not when the function runs.
That is why a function carries its surroundings with it wherever it goes, and that is exactly what a closure is.
Example
const college = "NIT";
function hostel() {
const room = 204;
function visitor() {
return college + " room " + room;
}
return visitor;
}
const f = hostel();
console.log(f()); // Output: NIT room 204
console.log(typeof room); // Output: undefinedvisitor is called outside hostel, yet it still sees room, because it was written inside it.
What to say in the interview
"Lexical scope means variable lookup is fixed by where a function is defined in the source. The engine looks in the current scope, then each enclosing scope, up to global. It does not depend on the call site, which is different from how this works."
Common mistakes
- Believing scope depends on where a function is called from.
- Expecting an outer function to read variables declared inside an inner one.