Lexical In JavaScript
Hi, am a passionate programmer and front-end web developer I am interested in problem solving
As mentioned in the MDN Docs
“Lexical scope uses the location where a variable is declared to determine where it is available,”
it sounds redundant — because if you already know where it is declared,
then it feels obvious that you also know where it will be available, right?
But the key is this 👇
🧠 “Declared” vs “Available” are two different perspectives
| Term | Meaning |
| Declared | Where the variable is physically created (written in code). |
| Available | In which other parts of the code (inner scopes) that variable can be accessed. |
So:
Declaration → defines the origin of the variable.
Availability → defines the range (the set of scopes) that can see it.
⚙️ How lexical scope works internally
When the code is parsed, JavaScript creates a scope chain — a hierarchy of environments.
Example:
function outer() {
let x = 10;
function inner() {
console.log(x);
}
inner();
}
Here’s what happens step-by-step:
JavaScript sees where
xis declared — insideouter().It then builds a scope chain —
inner()is nested insideouter().Because of that nesting,
x(declared inouter) is available insideinner.
So yes — it knows where it’s declared,
but it must determine which scopes are nested within that declaration to know who can access it.
That “determination” is what the definition is referring to.
🪄Think of it like:
Knowing where a key is made (declared)
doesn’t automatically tell you which doors it opens (available).
You must still check the structure of rooms (scope nesting) to figure out that.
🔍 Another quick example
let a = 1;
function outer() {
let b = 2;
function inner() {
let c = 3;
console.log(a, b, c);
}
inner();
}
outer();
Here:
adeclared globally → available everywhere.bdeclared inouter→ available only inouterand its children (likeinner).cdeclared ininner→ available only ininner.
So, even though we know where each variable is declared,
JavaScript still needs to analyze the lexical structure (which function is nested inside which)
to determine the scope of accessibility.
🧩 In short:
Lexical scoping first finds where a variable is declared,
then uses the code’s structural nesting to determine which inner functions can access it.
That second step — figuring out “where it’s available” — is necessary
because variables declared in outer scopes can flow inward,
but not outward.