Reputation: 1892
For example:
var myObj = {
yes: undefined
}
console.log(typeof myObj.yes === 'undefined') //--> true
console.log(typeof myObj.nop === 'undefined') //--> true too
Is there a way to detect if myObj.nop is not defined as undefined ?
Upvotes: 2
Views: 80
Reputation: 1605
var myObj = {
yes: undefined
}
console.log( myObj.yes === undefined); // gives true
and
var myObj = {
yes: 'any value here'
}
console.log( myObj.yes === undefined); // gives false
One thing to note here is that the undefined is not in single quotes. May be this gives you right direction.
Upvotes: 0
Reputation: 25820
Use hasOwnProperty
.
myObj.hasOwnProperty('yes'); // returns true
myObj.hasOwnProperty('nop'); // returns false
Upvotes: 1
Reputation: 19772
You would use in
:
if('yes' in myObj) {
// then we know the key exists, even if its value is undefined
}
Keep in mind, this also checks for properties in the object's prototype, which is probably fine in your case, but in case you only want to check properties that are directly set on that specific object, you can use Object.prototype.hasOwnProperty
:
if(myObj.hasOwnProperty('yes')) {
// then it exists on that object
}
Here's a good article on the difference between the two.
Upvotes: 5