Patternite Logo

Check if a property exists in a JavaScript object


A set of three simple patterns to check if a particular property exists in a JavaScript object, and the associated caveats


First approach: hasOwnProperty

As the name suggests, hasOwnProperty determines if an object has defined its own property, as opposed to inheriting it. Since all JavaScript objects inherit a prototype, methods like toString will not be identified by hasOwnProperty. These MDN docs give a good overview of hasOwnProperty.

Second approach: in operator

Unlike the hasOwnProperty method, the in operator also checks the object's inherited properties, so methods like toString present in the prototype will be identified.

Third approach: check if property is not undefined

This approach is similar to the in operator, however properties may be exist on the object but actually have a value of undefined, in which case this approach will return false. Depending on the usecase, this may or may not be desirable.

This blog post by Dmitri Pavlutin explains these three approaches in greater detail.

Profile picture for duncster

Patternite © 2021

Patternite Logo