Okay, so let's say that I have a global variable myVar, and in a function myFunction(), I write myVar = 2;. Normally, this will make myVar be equal to 2 inside the function. My question is, will declaring window.myVar = 2 in the function make myVar equal to 2 globally (so, alert(myVar) outside the function returns 2)?
- 6,976
- 2
- 26
- 48
- 33
- 1
- 6
-
That's not a declaration, it's an assignment to the property of the global object. – Bergi Nov 20 '17 at 23:38
-
^^ Agreed .. And being assigned to the global object it's accessible from anywhere .. – Zak Nov 20 '17 at 23:39
-
"*If I write `myVar = 2;` in a function, normally, this will make `myVar` be equal `2` inside that function*" - Nope. That's [when you use `var`](https://stackoverflow.com/q/1470488/1048572). – Bergi Nov 20 '17 at 23:40
-
Really? Because I just tested that in JSFiddle (my code: `var myVar; function myFunction () { myVar = 2; } alert(myVar);` and it returns "undefined" – Dreadnought Nov 21 '17 at 00:01
-
1You have to call `myFunction` as well :) – traktor Nov 21 '17 at 01:00
1 Answers
A quick review of global variables first:
Global variables declared using var or let behave differently. A global variable defined using var create a non-configurable property of the global object, using the name of the variable, which can't be deleted.
var x = "var x";
console.log("window.x: " + window.x);
console.log( JSON.stringify(Object.getOwnPropertyDescriptor(window, "x")))
But a global variable declared with let does not become a property of the global object. If you have a window property (in a browser) and a let variable of the same name, you have to qualify the window property with window. to access it:
let y = "let y";
window.y = "window.y";
console.log("y = " + y + "( using the identifier only)");
console.log("window.y = " + window.y);
Now getting back to the question,
If you declare
myVarin global scope and reference it within a function, you will access the global variable, provided you have not re-declared the variable within the function or any outer nested function. Without redeclaraion, such access works for both reading and writing and executingmyVar = 2within the function will update the value of the global variable.Executing
window.myVar = 2within a function will only update the value of a globalmyVarvariable if it was declared usingvar. It may create a window property but will not update the value of a globalletvariable.
So the value of myVar shown in an alert after the function has been called depends on
- whether the global declaration has been shadowed by re-declaring the variable within function scope (either locally within a function or in an outer function),
- whether
myVarwas referenced using an unadorned identifier or as a named window property, in conjunction with - whether
myVarwas originally declared usingvarorlet.
- 17,588
- 4
- 32
- 53