Lexical Environment

Lexical Environment in JavaScript is created every time you create a scope using the curly brackets {}. It can be nested: {{…}}

The lexical environment entails all of the outers scopes available to the current context.

Let’s look at an example:

For function ‘a’, its outer environment is the global environment, it sees myVar = 1;

The function ‘b’ its outer environment is that of function a where a’s myVar is hoisted and assigned to 2.

Its reference to the outer environment is function ‘a’ scope.

Thus, when function b is invoked, myVar will be 2.

Example 2

In this example, let’s try to invoke b in the global scope. In this lexical environment, b was never defined, and thus, you’ll get an error saying ‘b was never defined’.

Example 3

In this example, we see the global context has function ‘a’ defined and myVar.
We invoke function ‘a’, which then defines function b. Then it invokes b().

In function b, we log myVar.

Now, in this situation, its outside reference is function ‘a’.
However, myVar is not defined in function ‘a’.
Now we go down the scope chain and it looks at function ‘a’s outer reference. It sees that myVar is defined and assigned 1.

Thus, it look log 1.

This is going up the scope chain.