⊗jsPmClLEA 258 of 502 menu

Functions lexical environment applying in JavaScript

Suppose we have a function that returns another function as its result:

function test() { return function() { } }

If the parent function has any variables, then those variables will be contained in the lexical environment of the returned function:

function test() { let num = 1; // the parent function variable return function() { // lexical environment = {num: 1} } }

Let's write an alert in the code of our returned function that displays the value of the variable num in the console:

function test() { let num = 1; return function() { console.log(num); } }

Let's now call the parent function test and write the result of its work into the variable func:

function test() { let num = 1; return function() { console.log(num); } } let func = test();

The returned function will be written to the variable func. Let's call our function - as its result, it will display the contents of the variable num:

function test() { let num = 1; return function() { console.log(num); } } let func = test(); func(); // shows 1

If you just try to display the variable num outside the function, it will be unavailable:

function test() { let num = 1; return function() { console.log(num); } } console.log(num); // the variable num is not available here

As you can see, the local variable num is bound to the lexical environment of our function, and now, by calling this function anywhere in the code, we can get the value of the variable num, even if at the place of the call this variable is not available by itself.

In fact, a similar result can be achieved by making the variable num global:

function test() { return function() { console.log(num); } } let num = 1; // the global variable let func = test(); func(); // shows 1

Here, however, there will be a significant difference: in the new version, the variable num can be changed outside of functions (since it is global), but not in the old one.

Determine what will be output to the console without running the code:

function test() { let num1 = 1; let num2 = 2; return function() { return num1 + num2; } } let func = test(); console.log(func());

Determine what will be output to the console without running the code:

function test() { let num1 = 1; let num2 = 2; return function() { return num1 + num2; } } console.log(test()());

Determine what will be output to the console without running the code:

function test() { let num1 = 1; return function() { return num1 + num2; } } let num2 = 2; let func = test(); console.log(func());

Determine what will be output to the console without running the code:

function test() { let num = 1; return function() { return num; } } let num = 2; let func = test(); console.log(func());
enru