What is the correct way to check if a global variable exists?

Ebrahim Byagowi picture Ebrahim Byagowi · Jul 22, 2012 · Viewed 42.8k times · Source

JSLint is not passing this as a valid code:

/* global someVar: false */
if (typeof someVar === "undefined") {
    var someVar = "hi!";
}

What is the correct way?

Answer

bigoldbrute picture bigoldbrute · Jul 22, 2012
/*global window */

if (window.someVar === undefined) {
    window.someVar = 123456;
}

if (!window.hasOwnProperty('someVar')) {
    window.someVar = 123456;
}