Lexical Environment

Lexical Environment

What is lexical environment?

  • Lexical environment is made up of local memory and reference to the outer lexical environment.
  • Every time an execution context is created, a lexical environment is created along with it.

    Let's try to understand using a small program.

    let str = "Global Variable";
    f1();
    
    function f1() {
      f2();
      function f2() {
        console.log(str)
      }
    }
    

    Output.

    Screenshot 2022-09-14 at 5.00.23 PM.png

    How does the f2 function print the str declared in global scope??

    • Let's break it down with a diagram.

    Lexical-Enviornment.png

    1. When we execute the program, a global execution context is created, as well as a lexical environment.(The red box represents the lexical environment.)
    2. Memory allocation happened for the str variable and the function f1.
    3. The f1 function was then executed. which again created a new execution context for the f1 function and its own lexical environment.
    4. Memory allocation and f2 function invocation happened inside the f1 function, which again created an execution context and lexical environment for the f2 function.
    5. The f2 function requires the value of str, which it attempts to locate in its local memory but cannot find.
    6. So it tries to find it by referring to the outer lexical environment, but the value of str is still missing.
    7. It now goes one step above the outer lexical environment to find the str value. which is present.
    8. The f2 function fetches the value of str and prints it to the console.

This is how the lexical environment assisted the f2 function in retrieving the value of str from the global scope.