JSLint is not passing this as a valid code:
/* global someVar: false */
if (typeof someVar === \"undefined\") {
var someVar = \"hi!\";
}
<
/*global window */
if (window.someVar === undefined) {
window.someVar = 123456;
}
if (!window.hasOwnProperty('someVar')) {
window.someVar = 123456;
}
bfavaretto is incorrect.
Setting the global undefined to a value will not alter tests of objects against undefined. Try this in your favorite browsers JavaScript console:
var udef; var idef = 42;
alert(udef === undefined); // Alerts "true".
alert(idef === undefined); // Alerts "false".
window.undefined = 'defined';
alert(udef === undefined); // Alerts "true".
alert(idef === undefined); // Alerts "false".
This is simply due to JavaScript ignoring all and any values attempted to be set on the undefined variable.
window.undefined = 'defined';
alert(window.undefined); // Alerts "undefined".
/**
* @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.
This would be a simple way to perform the check .
But this check would fail if variableName
is declared and is assigned with the boolean value: false
if(window.variableName){
}