1

I have this object:

const obj = {
  k1: 1,
  k2: 2
};

which of these 2 methods is the correct one to check if a key doesn't exist, and why?

if (obj.k3 === undefined)

or:

if (typeof obj.k3 === 'undefined')

Is there a better method?

1
  • Could also do Object.keys(obj).includes('k3') Commented Apr 28, 2018 at 10:00

2 Answers 2

1

You may consider to use the in operator.

The in operator returns true if the specified property is in the specified object or its prototype chain.

const obj = {
        k1: undefined,
        k2: 2
    };

console.log('k1' in obj);                   //  true
console.log('k3' in obj);                   // false  <--- 

// value check
console.log(obj.k1 === undefined);          //  true
console.log(obj.k3 === undefined);          //  true

// typeof check
console.log(typeof obj.k1 === 'undefined'); //  true
console.log(typeof obj.k3 === 'undefined'); //  true

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

5 Comments

And what about "typeof"?
it returns the same as with direct check, please see edit.
Thank you for the great answer and the quick reply! So, in essence, there is no difference between direct check and "typeof". So why was typeof created in the first place? What's unique in it?
You cannot do if (foo === undefined) for an undeclared variable, it will give an undefined error, but you can do if (typeof foo === 'undefined').
@MSomerville, the later does not work either, because the access of an undeclared variable throws an error in strict mode.
0

you can use the Object.hasOwnProperty check function which will return or false,

//since k2 exists in your object it will return true, and your if condition will //be executed
if(obj.hasOwnProperty('k2')){
  //perform your action
  //write your code
}

//since k3 does not exists in your object it will return false, and your else //condition will be executed
if(obj.hasOwnProperty('k3')){
}else{
  //perform your action 
  //write your code
}

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.