0

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 ?

but-why
  • 533
  • 3
  • 10
  • 2
    Checking the property value is fast. It can be used when you can be sure the data doesn't contain falsy values. `.hasOwnProperty()` is slow, you can use `in` operator too. – Teemu Feb 02 '21 at 12:54
  • @Teemu Is ```key in obj``` equivalent to ```obj[key] === undefined``` ? – but-why Feb 02 '21 at 12:58
  • In some cases you could also use the [nullish coalescing operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator) – Reyno Feb 02 '21 at 12:58
  • 2
    @but-why No, `'a' in ({a: undefined})` is `true` whereas `({a: undefined})['a'] !== undefined` is `false`. (Assuming you meant `!==` instead of `===`.) – Ivar Feb 02 '21 at 13:09

2 Answers2

0

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

Shivansh Seth
  • 311
  • 1
  • 8
0

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
marcos
  • 4,473
  • 1
  • 10
  • 24