Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Testing for undefined throws var is not defined error...?

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).

like image 238
mtyson Avatar asked Feb 20 '11 19:02

mtyson


1 Answers

That's pretty weird. What about:

if (window['x']) {
   // It's defined
}

Does the above work? Also, what browser or JavaScript interpreter is this?

like image 162
Michael Aaron Safyan Avatar answered Oct 16 '22 02:10

Michael Aaron Safyan