Search code examples
javascriptpropertieshasownpropertytruthiness

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


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 ?


Solution

  • 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