Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing local variable with name of a global variable isn't possible in JS?

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

This code gives a result empty string. Why cannot JS reassign a local variable with same name as a global variable? In other programming languages the expected result is of course "foobar", why does JS behave like that?

like image 718
GirginSoft Avatar asked Aug 25 '11 06:08

GirginSoft


People also ask

Can a local variable and a global variable have the same name?

A program can have the same name for local and global variables but the value of a local variable inside a function will take preference. For accessing the global variable with same rame, you'll have to use the scope resolution operator.

What happens if a local variable exists with the same name as the global variable you want to access 1 point?

What happens if a local variable exists with the same name as the global variable you want to access? Explanation: If a local variable exists with the same name as the local variable that you want to access, then the global variable is shadowed. That is, preference is given to the local variable.

Can a function have a local variable with the same name as a global variable in python?

Python allows the declaration of Local variable with the same name as Global variable.

Can local variable override global variables?

LOCAL variables are only accessible in the function itself. So, in layman's terms, the GLOBAL variable would supersede the LOCAL variable in your FIRST code above.


1 Answers

That's because you declared a local variable with the same name - and it masks the global variable. So when you write foo you refer to the local variable. That's true even if you write it before the declaration of that local variable, variables in JavaScript are function-scoped. However, you can use the fact that global variables are properties of the global object (window):

var foo = window.foo || "";

window.foo refers to the global variable here.

like image 56
Wladimir Palant Avatar answered Sep 19 '22 06:09

Wladimir Palant