JavaScript: Check if an Object Property exists Programming 23 FEB 2016

A lot of warnings in code that I have to maintain often stem from the fact that the initial developer never bothers checking whether or not a given property of an object exists before trying to use it.

We’ve got a couple of options available to us to check whether or not a property actually exists in a given object, including the simple checking on whether or not the typeof returns ‘undefined’, or even using a basic in to check.

In practice (checking if property name exists in object user):

//Example of 'typeof' check - 
//Note: Of course, this could provide a false positive if the property value is actually set to 'undefined'
if (typeof === 'undefined') {
console.log('name property is missing');

//Example of 'in' check
if (!('name' in user)){
console.log('name property is missing');

A better, although slightly more costly (in terms of speed) check is to use the hasOwnProperty() method, which checks if the object on its own (not through one of its ancestors) has the given property or not.

In practice:

//Exammple of 'hasOwnProperty' check
if (!user.hasOwnProperty('name')) {
    console.log('name property is missing');

Of course, you probably should probably also check that the actual object itself exists first!

chimpanzee using a laptop to fix a problem

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.