bluehost-banner

How to Check If a Property Exists in an Object

In this tutorial, you will learn how to check if a property exists in an object.

JavaScript provides a hasOwnProperty() method that returns true if a property exists in an object:

let result = targetObject.hasOwnProperty(propertyName);

 

Below we have declared sample users object:

 
let users= {
   firstName: 'ravi',
   lastName: 'vikas'
};

Now we have uses the hasOwnProperty() method to check if the firstName property exists in the usersobject:

let result = users.hasOwnProperty('firstName');
console.log(result); // true

Now, the dob the property does not exist in the users object, therefore, the following code will return false,see below example:

let result = users.hasOwnProperty('dob');
console.log(result); // false