How to check if a property is defined in an object#
ReferenceError). In case you didn't know already, here is a refresher.
Note the use of a quoted 'undefined' instead of the
typeof operator always returns a string.
So how do we check if a property is defined in an object or not? Quick common sense might suggest you can do this:
It even works. So this might just be the way to check for undefined properties in objects too.
Do not use that method to check if a property is defined in an object or not!
The reason is this:
There is a possibility that the value of the property itself is
undefined, in which case we'll end up with a false positive for our condition check. Similarly don't count on
The reliable way of checking if a property exists in an object or not is using the
hasOwnProperty() method. This method check if the object, on its own, not through one of its ancestors, has the property or not. In our case, we need to do this: