Is javascript a realistic lexical reach?

Why does this return 2 instead of 1? It seems that the second "var" is silently ignored.

function foo() { var local = 1; { var local = 2; } return local; } foo() /* 2 */ 
+5
source share
2 answers

In javascript, there is only a level scope and a global scope. you cannot create a block region and does not add special value and does not create any region.

And this is how your code ends

 function foo() { var local = 1; local = 2; return local; } foo(); 

In ES6, you can create block level areas with Let . ES6 is not yet supported. more about this here

+5
source

From MDN :

JavaScript does not have a block scope; rather, the variable declared inside the block is local to the function (or global scope) that the block is inside.

The scope of a variable in JavaScript is the whole function in which it is declared (or the global scope), so there is only one local variable here.

Your code is equivalent

 function foo() { var local; local = 1; { local = 2; } return local; } foo() 

Note that ES6 (the new JavaScript norm) introduces a lexical definition with let , but it is not yet available .

+3
source

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


All Articles