This is a short JavaScript tutorial on how to check if an object property exists.
In order to achieve this, we will use the Object.prototype.hasOwnProperty() method.
Take a look at the following example.
//Check to see if our object has a certain property. if(myObject.hasOwnProperty("property_name")){ alert(myObject.property_name); }
If the property in question exists, this method will return a boolean TRUE value. If it does not exist, then it will return FALSE.
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.
Now, let’s check to see if the object has a property called “dob”.
//Check to see if our object has a certain property. if(user.hasOwnProperty("dob")){ 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 browser console will read as follows.
user object has property dob
Finally, let’s check for an object property that does not exist.
//An example. This time, we check for a property that does not exist. if(user.hasOwnProperty("email")){ 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 this method is that all major browsers support it.
Furthermore, it will return TRUE even if the property in question is NULL or undefined.
You will probably find other solutions floating around on the web. However, the current consensus among JavaScript developers is that you should use the hasOwnProperty method.