window.variableName

window.variableName means that the variable is being declared at the global scope. This means any JS code will have access to this variable. Using window. is not necessary but is frequently used as a convention to denote that a variable is global.

Globals are generally to be avoided. You should define variables within the scope of functions.


Global variables in JavaScript are attached to the "global object", which in a browser environment is aliased to window object - this is why you can refer to a global variable either as variableName or window.variableName.

It's also worth mentioning that using global variables in JavaScript is not considered good coding practice.

Here's a good and very detailed explanation.


window.myVar or window["myVar"] is an explicit way to refer to a global variable.

A variable is a global variable if it's declared outside of a function (with or without "var"), or if it's declared inside a function without using "var", or if it's declared as window.myVar or window["myVar"].

A variable is declared by either assigning a value to it, or by using the keyword var.

One case where it's useful to refer to a global variable as window.myVar is if you're inside a function that has a local variable called myvar. In that case, myVar refers to the local variable, while window.myVar refers to the global variable.

Tags:

Javascript