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.
How does the
f2
function print thestr
declared in global scope??- Let's break it down with a diagram.
- When we execute the program, a global execution context is created, as well as a lexical environment.(The red box represents the lexical environment.)
- Memory allocation happened for the
str
variable and the functionf1
. - The
f1
function was then executed. which again created a new execution context for thef1
function and its own lexical environment. - Memory allocation and
f2
function invocation happened inside thef1
function, which again created an execution context and lexical environment for thef2
function. - The
f2
function requires the value ofstr
, which it attempts to locate in its local memory but cannot find. - So it tries to find it by referring to the outer lexical environment, but the value of
str
is still missing. - It now goes one step above the outer lexical environment to find the
str
value. which is present. - 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.