JavaScript check if object has property | Example code

  • by

You can use the hasOwnProperty() method or in operator or Compare with undefined to check if the object has property in JavaScript.

x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
    //Do this
}

The hasOwnProperty() method returns true if a property exists in an object:

JavaScript check if the object has a property

Simple example codes to check for property existence in a JavaScript object.

hasOwnProperty() method

<!DOCTYPE html>
<html>
<body>

  <script>
   var x = {
    'key': 1
  };

  if ( x.hasOwnProperty('key') ) {
    console.log('has key with value',x['key']);
  }
</script>

</body>
</html> 

Output:

JavaScript check if object has property

in operator

var x = {
  'key': 1
};

if ('key' in x) {
  console.log('has');
}

Comparing with undefined

You can use the typeof operator to directly check the data type of the object property:

if (typeof x.key === "undefined") {
    console.log("undefined");
}

How to check if an object has any properties in JavaScript?

Answer: You can use the built-in Object.keys method to get a list of keys on an object and test its length.

var x = {};
// some code where value of x changes and than you want to check whether it is null or some object with values

if(Object.keys(x).length){
 // Your code here if x has some properties  
}

Or can loop over the properties of your object as follows:

for(var prop in ad) {
    if (ad.hasOwnProperty(prop)) {
        // handle prop as required
    }
}

It is important to use the hasOwnProperty() method, to determine whether the object has the specified property as direct property, and is not inherited from the object’s prototype chain.

Do comment if you have any doubts or suggestions on this Js object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.