Is !obj[key] a good practice to check the existence of an object's property in JavaScript?

750 Views Asked by At

Every now and then, I see this pattern:

if (!obj[key]) {
    // key does not exist inside object
    obj[key] = ...
} else {
    // maybe do something else with obj[key]
}

but I find it extremely wrong. What if actually obj[key] has the value false or '' ? Then the code doesn't make any sense to me.

Is there a reason I see this so often ? Why people don't use .hasOwnProperty() to check whether or not a key exists as a property of an object ?

2

There are 2 best solutions below

0
On BEST ANSWER

You should use the in operator:

"key" in obj // true, regardless of the actual value

if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty:

obj.hasOwnProperty("key") // true

For performance comparison between the methods that are in, hasOwnProperty and key is undefined, check this reference

0
On

You are right, if you are checking if the key prop exists, then definitely should no use it, there are better options, for example .hasOwnProperty or the in operator, for example:

const obj = { a: '' }

console.log('is key a in obj?', obj.hasOwnProperty('a'))
>>> true
console.log('is key a in obj?', 'a' in obj)
>>> true
console.log('is key a in obj?', Boolean(obj['a']))
>>> false // it's wrong, like u mentioned

console.log('is key b in obj', obj.hasOwnProperty('b'))
>>> false
console.log('is key b in obj', 'b' in obj)
>>> false
console.log('is key b in obj', Boolean(obj['b']))
>>> false