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:

//Example user object.
var user = {
    name: 'Sara Hudson',
    gender: 'Female',
    dob: '1991-03-12'

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?

//Check to see if our object has a certain property.
    console.log('user object has property dob');
} else{
    console.log('user object does NOT have property dob');

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”:

//An example. This time, we check for a property that does not exist.
    console.log('user object has property email');
} else{
    console.log('user object does NOT have property 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