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 1:
/*global window */
if (window.someVar === undefined) {
window.someVar = 123456;
}
if (!window.hasOwnProperty('someVar')) {
window.someVar = 123456;
}
Solution 2:
/**
* @param {string} nameOfVariable
*/
function globalExists(nameOfVariable) {
return nameOfVariable in window
}
It doesn't matter whether you created a global variable with var foo or window.foo — variables created with var in global context are written into window.
Solution 3:
If you are wanting to assign a global variable only if it doesn't already exist, try:
window.someVar = window.someVar || 'hi';
or
window['someVar'] = window['someVar'] || 'hi';