JavaScript: Check if object property exists.

This is a short JavaScript tutorial on how to check if a given object property exists. In order to achieve this, we will use the Object.prototype.hasOwnProperty() method.

Let’s create an example JavaScript object:

In the snippet above, we created a simple JavaScript object that represents a user. This object contains three properties: name, gender and dob.

What if we want to check to see if the dob property exists before we attempt to access it?

If you run the code above, you will see that the object property “dob” exists and the output in the console will read:

user object has property dob

Now, let’s check for an object property that does not exist. Let’s check for a property called “email”:

In this case, the property “email” does not exist. Therefore, you should see the following output in your browser console:

user object does NOT have property email

The best thing about the Object.prototype.hasOwnProperty() method is that it is supported by all major browsers, except for a few older rarely-used versions of Safari.

You will probably find other solutions floating around on the web. However, the current consensus among JavaScript developers is that the hasOwnProperty method should be used. Unless, of course, you have found a specific reason to avoid it.

Facebook Comments