This post will discuss how to verify if an object has a certain property in JavaScript.

There are several ways to check whether an object contains a specific property in JavaScript. Here are some of the possible options:

1. Using Object.prototype.hasOwnProperty() function

JavaScript already provides a built-in function Object.prototype.hasOwnProperty() for checking if an object contains the specific property or not. The hasOwnProperty() function returns true if the object has the specified property as their own property and not inherited, and false otherwise. In order words, the specified property should be attached to the object itself and not its prototypes. The following example determines whether the object obj contains the age property:

Download  Run Code

 
However, it is not completely full-safe to call the hasOwnProperty() function on the object. The above code will fail if the object has some property named hasOwnProperty. We can handle it by calling the Object.prototype.hasOwnProperty.call() function instead:

Download  Run Code

 
If we have an array of objects and want to check if any of the objects have the specified property, we can use it with the some() function. This function searches for atleast one element in the array that passes the test implemented by the provided function.

Download  Run Code

2. Using in operator

Another option is to use the in operator, which is a built-in operator that returns true if the property exists in an object, and false otherwise. For example:

Download  Run Code

 
If we have an object array and want to check if any of the objects have the specified property, we can do something like:

Download  Run Code

3. Using typeof operator

A third option is to use the typeof operator, which is a built-in operator that returns a string indicating the type of the value. We can use this operator to check if the property is not undefined, which means it exists in the object.

Download  Run Code

 
However, it is not completely safe to call this operator on the object, as it will not work if the property has an undefined value. For example:

Download  Run Code

That’s all about verifying if a object has a certain property in JavaScript.