Passing local variable with global variable name is not possible in JS?

foo = "foobar"; var bar = function(){ var foo = foo || ""; return foo; } bar();` 

This code gives an empty result line. Why can't JS assign a local variable with the same name as a global variable? In other programming languages, the expected result is, of course, "foobar", why does JS behave this way?

+4
source share
2 answers

This is because you declared a local variable with the same name - and it masks the global variable. Therefore, when you write foo , you are referencing a local variable. This is true, even if you write it before declaring this local variable, the variables in JavaScript are functional. However, you can use the fact that global variables are properties of a global object ( window ):

 var foo = window.foo || ""; 

window.foo here refers to a global variable.

+24
source

As soon as the interpreter sees var foo , it assumes that foo is a local variable. What for? The answer is simple: since this language was built. (and no, this is not the only language that works this way)

+2
source

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


All Articles