简体   繁体   中英

Do something if a variable is defined

In JS, I want to do something if a variable is defined or not. I was under the impression this syntax would work:

if (foo) {
    console.log('foo is defined');
} else {
    console.log('foo is not defined');       
}

But I get a "Uncaught Reference Error: foo is not defined":

http://jsfiddle.net/cfUss/

Am I missing something? I thought this was very basic js and had used this syntax a ton before.

Check its type :

if (typeof(foo) != 'undefined')

Your check only works if the variable is declared and falsey , but you need to know if the object is even defined .

There are two related concepts, being declared and being defined. Trying to reference a name which is not declared is what throws the error, not trying to reference a value which is undefined.

So for example:

var foo; //Declare the variable. It's still not defined however
if (foo) {
    console.log('foo is defined');
} else {
    console.log('foo is not defined');       
}

Of course, if I actually want to detect something which is undeclared or undefined as you mention you want to do, I usually prefer to be more explicit and use if(typeof foo != "undefined") since var foo; if (foo) var foo; if (foo) doesn't trigger for defined but falsey values. Finally, you can do direct comparison to an undefined value if you want to test whether something is undefined and allow it to throw if undeclared, eg if(foo !== void(0))

if (typeof foo == "undefined") {
     console.log('doesnt exist');  
} else {
     console.log('it exists');   
}

http://jsfiddle.net/cfUss/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM