Lexical Environment

In JavaScript, lexical environment is a data structure that holds variable and function declarations during the execution of the program.

It consists of two main components: an environment record and a reference to the outer environment (aka outer/parent scope).

The environment record is a record of all the variables and functions defined within the current scope. It stores the identifiers and their corresponding values/references. When a variable is accessed, the environment record is consulted to retrieve its value.

The outer environment reference points to the outer/parent scope of the current scope. It allows for the chaining of scopes, creating a hierarchical structure known as the scope chain.

Lexical environments play a crucial role in variable scoping and function closures in JavaScript. They determine how variables are accessed and resolved within nested scopes, and they maintain the relationship between different scopes in the code.

When does a new lexical environment gets created?

In JavaScript, a new lexical environment is created mainly in two scenarios as mentioned below.

When a JavaScript program starts running, a global lexical environment is automatically created.

Each time a function is invoked, a new lexical environment is created specifically for that function invocation. This lexical environment, sometimes referred to as function’s execution context, holds the local variables, functions declarations, and the value of this for that specific invocation of the function.

How does a new lexical environment gets created?

The creation of a lexical environment involves three steps:

  1. Creation of environment record.
  2. Capturing the outer environment reference.
  3. Assigning appropriate this value (for function contexts), based on how the function is called.

Lexical environments play a crucial role in scoping and variable access, as they determine the visibility and lifetime of variables and functions within different parts of the code.