How to check if a property is defined in an object#

Probably you know how to check if a variable is defined in JavaScript or not (without crashing your app with a fatal ReferenceError). In case you didn't know already, here is a refresher.

Wrong:

Run
Clear

Right:

Run
Clear

Note the use of a quoted 'undefined' instead of the undefined JavaScript keyword. That is because 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:

Run
Clear

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:

Run
Clear

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 null and false.

Even harder to debug - if the key in question is found in the object's prototype chain (parent or one of the 'ancestors'), we end up with a false positive result again. The JavaScript interpreter looks for a property in an object, if not found, it looks for the property in the prototype chain. If this scenario didn't make any sense to you, you need to look up Prototypal Inheritance.

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:

Run
Clear

Hope this little info saves you from hours of frustration and headache as a JavaScript developer.

Tweet this | Share on LinkedIn |