2

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 ?

1
  • 1
    Because type of undefined is undefined. Use hasOwnProperty instead. Commented Sep 24, 2015 at 16:45

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Use hasOwnProperty.

myObj.hasOwnProperty('yes');             // returns true
myObj.hasOwnProperty('nop');         // returns false

1 Comment

I was about to key it
0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.