Skip to main content

Command Palette

Search for a command to run...

Lexical In JavaScript

Published
•2 min read•View as Markdown
N

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

TermMeaning
DeclaredWhere the variable is physically created (written in code).
AvailableIn 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:

  1. JavaScript sees where x is declared — inside outer().

  2. It then builds a scope chain — inner() is nested inside outer().

  3. Because of that nesting, x (declared in outer) is available inside inner.

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:

  • a declared globally → available everywhere.

  • b declared in outer → available only in outer and its children (like inner).

  • c declared in inner → available only in inner.

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.