javascriptglobal-variablesjslint

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


JSLint is not passing this as a valid code:

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

What is the correct way?


Solution

  • /*global window */
    
    if (window.someVar === undefined) {
        window.someVar = 123456;
    }
    
    if (!window.hasOwnProperty('someVar')) {
        window.someVar = 123456;
    }