This is an oddity I've seen occasionally in JS - maybe someone can shed light on it.
I do a test for undefined on a variable:
if (x !== 'undefined'){}
or even
if (typeof x !== 'undefined'){}
And the browser still throws an error:
ReferenceError: x is not defined
Even
if (x) {}
throws the error.
This is a framework-level global variable I am checking for, so possibly something to do with different scopes. (No critiques of global variables - again, its the existence of a framework I'm testing for).
3 Answers 3
That's pretty weird. What about:
if (window['x']) {
// It's defined
}
Does the above work? Also, what browser or JavaScript interpreter is this?
3 Comments
if(variable) actually checks for a value and also works to check for possibly non-existing properties: if(obj.variable). If a 'naked' variable might not be declared, its existance can safely be checked with if (typeof(variable) == "undefined").@Anurag is right the second condition should not through error.
if (typeof x !== 'undefined'){// won't through error even if x is not declared
}
I guess the problem is that x is not declared as a variable. If you declare it but leave it unassigned it is treated as undefined and won't through error, in your case it is not declared.
var x;
if (x !== undefined){// won't through error
}
Objects fields are treated differently
if(window.x !== undefined){// won't through error
}
it seems like x in this case is declared in runtime if not found, so returns undefined
Hope this helps!
2 Comments
Your problem is that undefined !== 'undefined'
2 Comments
typeof x === 'undefined' ;)typeof x !== 'undefined'. Good luck testing other browsers
typeof x !== 'undefined'should not throw a ReferenceError.typeof xfor anyx.