⊗jsPmClLE 259 of 504 menu

Lexical environment of functions in JavaScript

All external variables available to the function are called its Lexical Environment

In the following function example, two variables are available: num1 and num2, which are the lexical environment of our function:

let num1 = 1; let num2 = 2; function func() { // the function knows about the variables num1 and num2 }

The lexical environment itself is some kind of internal JavaScript object attached to our function. In this case, it can be represented as follows:

{num1: 1, num2: 2}

The value of any lexical environment variable is always equal to the current value of that variable:

let num1 = 1; // environment {num1: 1} let num2 = 2; // environment {num1: 1, num2: 2} // Let's change the variable num1: num1 = 123; // environment {num1: 123, num2: 2} function func() { }

When we try to refer to some variable inside a function, this variable is first looked up among the local variables of the function and, if such a variable is not there, then it is looked up in the lexical environment of the function.

byenru