Dancer Dancer - 2 days ago 4
Javascript Question

How to declare a global variable in JavaScript?

How can I declare a global variable in JavaScript?

Answer

If you have to generate global variables in production code (which should be avoided) always declare them explicitly:

window.globalVar = "This is global!";

While it is possible to define a global variable by just omitting var (assuming there is no local variable of the same name), doing so generates an implicit global, which is a bad thing to do and would generate an error in strict mode.

Comments