simplesystems simplesystems - 4 months ago 18
Javascript Question

Javascript check if undefined doesnt work

I want to check if a object is defined or not..

content of the Object:

Object

so I'll do:

if (e.model.item.state != "undefined"){
var stateID = e.model.item.state.id;
....
}
else{

}


Then e.model.item.state is undefined but it does enter the if clause and stops here:

var stateID = e.model.item.state.id;


because of undefined..!

I tried also:

!== "undefined"
!=== "undefined"

Answer

In JS, you can check whether a variable is either undefined, null, false or 0 by just simply doing,

if (e.model.item.state) {
   // e.model.item.state is NOT `undefined`, `null`, `false` or `0`
}
else {
   // e.model.item.state is either `undefined`, `null`, `false` or `0`
}