[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 ?
We should instead use the in operator:
If we want to check if a key doesn't exist, remember to use parenthesis:
Or, if we want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty:
Solution 2:
It will return undefined
.
undefined is a special constant value. For e.g.
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
Solution 3:
This solution refers to Object. Using the in
operator on Array to find data instead of keys:
Solution 4:
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.)