Skip to content

Lexical environment in JavaScript

  • by

JavaScript lexical environment is a data structure that holds an identifier-variable mapping. Where identifier refers to the name of variables/functions, and variable is the reference to actual object. It also holds a reference to a parent lexical environment.

Lexical Environment: Local Memory + Lexical Environment of its Parent

Lexical in general means in a hierarchy or in a sequence. Whenever a new execution context(EC) is created a new lexical environment is created and it is referenced in the local EC in memory space.

The lexical environment in JavaScript

Simple example code variables and functions are live or physically present during the program execution.

<!DOCTYPE html>
<html>
<body>

  <script>
    // This is what a lexical environment conceptually look like:
    //LexicalEnvironment = {
      //Identifier:  <value>,
      //Identifier:  <function object>
    //}

    function a() {
      var b = 10;
      c();
      function c() {
        console.log(b); //it prints the right value.
      }
    }

    a();
    console.log(b); // prints NOT DEFINED!

  </script>

</body>
</html>

Output:

Lexical environment in JavaScript

function c is lexically inside function a.

  • So in EC of c(), variables and fun in c (none) + reference of lexical env of parent a() is there
  • LE of a() in turn is its memory space + reference to LE of parent (Global EC)
  • LE of Global EC points to its memory space + NULL (as no parent for Global EC).

Source: https://www.intervue.io/developer

How does JavaScript’s lexical environment maintain variable declarations within nested block scopes?

Answer: The block statement creates a new lexical environment.

A Lexical Environment is a specification type used to define the association of Identifiers to specific variables and functions based upon the lexical nesting structure of ECMAScript code. A Lexical Environment consists of an Environment Record and a possibly null reference to an outer Lexical Environment. Usually, a Lexical Environment is associated with some specific syntactic structure of ECMAScript code such as a function declaration, a BlockStatement, or a Catch clause of a try statement and a new Lexical Environment is created each time such code is evaluated.

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this Js Advanced topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *