[Solved-5 Solutions] Checking if a key exists in a javascript object - javascript tutorial



Problem:

How to check if a particular key exists in a JavaScript object or array ?

If a key doesn't exist, and we try to access it, will it return false ? Or throw an error ?

Solution 1:

Checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually undefined ?

var obj = { key: undefined };
obj["key"] != undefined // false, but the key exists!

We should instead use the in operator:

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

If we want to check if a key doesn't exist, remember to use parenthesis:

!("key" in obj) // true if "key" doesn't exist in object
!"key" in obj   // ERROR!  Equivalent to "false in obj"

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

obj.hasOwnProperty("key") // true

Solution 2:

It will return undefined.

var aa = {hello: "world"};
alert( aa["hello"] );      // popup box with "world"
alert( aa["goodbye"] );    // popup box with "undefined"

undefined is a special constant value. For e.g.

// note the three equal signs so that null won't be equal to undefined
if( aa["goodbye"] === undefined ) {
    // do something
}

This is probably the best way to check for missing keys. However, as is pointed out in a comment below, it's theoretically possible that you'd want to have the actual value be undefined. I've never required to try and do this and can't think of a reason offhand why I'd ever want to, but just for the sake of completeness, we can use the in operator

// this works even if we have {"goodbye": undefined}
if( "goodbye" in aa ) {
    // do something
}
;

Solution 3:

This solution refers to Object. Using the in operator on Array to find data instead of keys:

("true" in ["true", "false"])
// -> false (Because the keys of the above Array are actually 0 and 1)
"key" in obj

Is likely testing only object attribute values that are very different from array keys.

Solution 5:

Three ways to check if a property is present in a javascript object:

!!obj.theProperty

  • It Will convert value to bool. returns TRUE for all but the 'false' value

'theProperty' in obj

  • It Will return true if the property exists, no matter its value (even empty)

obj.hasOwnProperty('theProperty')

Does not check the prototype chain. (since all objects have the 'toString' method, 1 and 2 will return true on it, while 3 can return false on it.)


Related Searches to Checking if a key exists in a javascript object - javascript tutorial