Reputation: 2757
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?
Upvotes: 1
Views: 2275
Reputation: 386522
You may consider to use the in
operator.
The
in
operator returnstrue
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
Upvotes: 1
Reputation: 729
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
}
Upvotes: 0