Reputation: 849
I want to check if a object is defined or not..
content of the 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"
Upvotes: 0
Views: 141
Reputation: 9974
Better use this to avoid unnecessary undefined error
:-
if (e && e.model && e.model.item & e.model.item.state) {
// e.model.item.state is NOT `undefined`, `null`, `false` or `0`
}
Upvotes: 3
Reputation: 17858
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`
}
Upvotes: 2
Reputation: 10740
"undefined"
is not the same as undefined
. The first one is a string with the word 'undefined' in it, the other is a reserved js term for undefined var.
Doing something == "undefined"
is comparing it to a string. You should remove the quotes.
Upvotes: 2
Reputation: 10083
You check for undefined
in one of following ways:
var a;
if( a === undefined )
OR
if( typeof a === "undefined" )
"undefined"
is not equal to undefined
. So, if you compare directly for equality, use it without quotes. If you are using typeof
operator, you need to use quotes because typeof
always returns a string value.
Upvotes: 0