DEV Community

Abimanyu P
Abimanyu P

Posted on

Lexical Environment in JavaScript

Lexical Environment in JavaScript:

visual explaination

A Lexical Environment in JavaScript is a place where JavaScript keeps track of the variables and functions available in a particular scope. It also keeps a reference to the outer scope, so JavaScript can find variables that are not available in the current scope.

In simple words, you can think of a lexical environment as a storage area for variables and functions along with a link to the outer scope.

When is a Lexical Environment created?

A lexical environment is created for a scope. For example, when a function is called, JavaScript creates a new lexical environment for that function. This environment contains its parameters and local variables.

Consider this example:

function outer() {
  var x = 10;

  function inner() {
    console.log(x);
  }

  inner();
}

outer();
Enter fullscreen mode Exit fullscreen mode

Here, outer() has its own lexical environment, which contains x.
The inner() function has its own lexical environment, but it can also access the lexical environment of outer() because inner() was written inside outer().
So, inner() can find x even though x is not declared inside inner().

How does JavaScript find a variable?

When JavaScript sees a variable name, it first looks in the current lexical environment.
If it doesn't find the variable there, it looks in the outer lexical environment.
It continues moving outward until it finds the variable or reaches the global scope.

For example:

var name = "John";

function greet() {
  console.log(name);
}

greet();
Enter fullscreen mode Exit fullscreen mode

When JavaScript tries to find name inside greet(), it first checks greet()'s environment.
name is not there, so JavaScript looks in the outer environment. It finds name in the global environment.

The lookup works roughly like this:

greet() environment
       ↓
outer environment
       ↓
global environment
Enter fullscreen mode Exit fullscreen mode

If JavaScript cannot find the variable anywhere, it throws a ReferenceError.

console.log(age);
Enter fullscreen mode Exit fullscreen mode

Since age does not exist in any accessible lexical environment, JavaScript throws:

ReferenceError
Enter fullscreen mode Exit fullscreen mode

Why is it called "Lexical"?

The word lexical means that the scope of a variable is determined by where the code is written, not where the function is called.

For example:

function outer() {
  var x = 10;

  function inner() {
    console.log(x);
  }

  inner();
}
Enter fullscreen mode Exit fullscreen mode

Because inner() is written inside outer(), it has access to the variables of outer().This relationship is determined by the structure of the code.

Top comments (0)