Reputation: 33
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
)?
Upvotes: 3
Views: 65
Reputation: 19301
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 myVar
in 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 executing myVar = 2
within the function will update the value of the global variable.
Executing window.myVar = 2
within a function will only update the value of a global myVar
variable if it was declared using var
. It may create a window property but will not update the value of a global let
variable.
So the value of myVar
shown in an alert after the function has been called depends on
myVar
was referenced using an unadorned identifier or as a named window property, in conjunction withmyVar
was originally declared using var
or let
.Upvotes: 3