What is the correct way to check if a global variable exists?
try
variableName in window
or
typeof window[variableName] != 'undefined'
or
window[variableName] !== undefined
or
window.hasOwnProperty(variableName)
/**
* @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.
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';
/*global window */
if (window.someVar === undefined) {
window.someVar = 123456;
}
if (!window.hasOwnProperty('someVar')) {
window.someVar = 123456;
}