W3docs

How to Check if an Object has a Specific Property in JavaScript

Read this tutorial and learn the methods of checking whether the specified object has the specified property in JavaScript. Find the fastest one for you.

There are several methods of checking whether the object has a property or not in JavaScript. Let’s quickly explore them and find the fastest one.

The typeof Operator

Most developers use the typeof operator to check if the type of the property is undefined. If a property exists but holds the value undefined, <kbd class="highlighted">typeof</kbd> is not recommended.

Javascript typeof method with undefined

javascript— editable

Javascript typeof method with undefined

javascript— editable

The hasOwnProperty Method

Javascript object provides the <kbd class="highlighted">hasOwnProperty</kbd> native method. The method returns a boolean indicating whether the object has the specified property as a direct property.

Warning

The <kbd class="highlighted">hasOwnProperty</kbd> method does not check down the prototype chain of the object.

Javascript hasOwnProperty method

javascript— editable

The in Operator

The <kbd class="highlighted">in</kbd> operator returns true if it finds the specified property in the object.

Info

The <kbd class="highlighted">in</kbd> operator can be used both in objects and arrays.

Javascript "in" operator

javascript— editable

Benchmarks typically show that <kbd class="highlighted">typeof</kbd> is faster than <kbd class="highlighted">hasOwnProperty</kbd> and the <kbd class="highlighted">in</kbd> operator for simple existence checks, though the performance difference is negligible in most real-world applications.

hasOwnProperty vs in

The <kbd class="highlighted">hasOwnProperty</kbd> method returns a boolean, which shows whether the object contains the specified property or not.

This method determines whether the object has the specified property as a direct property of that object. Unlike the <kbd class="highlighted">in</kbd> operator, <kbd class="highlighted">hasOwnProperty</kbd> does not check for a property in the object's prototype chain. If an object is an Array, this method can check whether an index exists. If the specified property exists in the object or its prototype chain, the <kbd class="highlighted">in</kbd> operator returns true.