How to declare a global variable in JavaScript

Dancer picture Dancer · Jul 28, 2010 · Viewed 312.6k times · Source

How can I declare a global variable in JavaScript?

Answer

Felix Kling picture Felix Kling · Jul 28, 2010

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.