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:
It will return
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
This solution refers to Object. Using the
in operator on Array to find data instead of keys:
Is likely testing only object attribute values that are very different from array keys.
- 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)
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.)