JavaScript code execution after return

In the following example, JavaScript seems to completely ignore my return and just execute executable code.

 var x = 1; (function() { x = 2; return; var x = 3; })(); console.log(x); // Outputs 1 in both Chrome and FF 

Surely the code should output 2 ? If I remove the var keyword from var x = 3 , it will output 2 as expected. Is there any weird compiler optimization here?

+4
source share
1 answer

No, the code should not output 2, because variable declarations go up, so your code is equivalent

 var x = 1; (function() { var x; x = 2; // changes the internal x variable return; x = 3; // does nothing because it not reached })(); console.log(x); // Outputs the outside x, which is still 1 

Line

 x = 2; 

only changes the internal variable x , which obscures the external object.

The volume of a non-global variable is an integer function in which it is declared. From the beginning of this function to its end.

+8
source

Source: https://habr.com/ru/post/1494036/


All Articles