I am Hack Sparrow
Captain of the Internets.

JavaScript – Check Object Property is Defined

How to check if a property is defined in an Object

Probably you know how to check if a variable is defined in JavaScript or not (without crashing your app with a fatal ReferenceError). In case you didn't know already, here is a refresher.

Wrong:

if (username == undefined) {
console.log('username missing');
}
else {
console.log(username);
}

Right:

if (typeof username === 'undefined') {
console.log('username missing');
}
else {
console.log(username);
}

Not the use of a quoted 'undefined' instead of the undefined JavaScript keyword. That is because the typeof operator returns a string, and no other data type.

So how do we check if a property is defined in an object or not? Quick common sense might suggest you can do this:

var user = {name:'Apple'};
if (typeof user.name === 'undefined') {
console.log('name property is missing');
}

It even works. So this might just be the way to check for undefined properties in objects too.

DO NOT use that method to check if a property is defined in an object or not. The reason is this:

var user = {name:undefined};
if (typeof user.name === 'undefined') {
console.log('name property is missing');
}

There is a possibility that the value of the property itself is undefined, in which case we'll end up with a false positive for our condition check. Similarly don't count on null and false.

Even harder to debug - if the key in question is found in the object's prototype chain (parent or one of the 'ancestors'), we end up with a false positive result again. The JavaScript interpreter looks for a property in an object, if not found, it looks for the property in the prototype chain. If this scenario didn't make any sense to you, you need to look up Prototypal Inheritance.

The reliable way of checking if a property exists in an object or not is using the hasOwnProperty() method. This method check if the object, on its own, not through one of its ancestors, has the property or not. In our case, we need to do this:

if (!user.hasOwnProperty('name')) {
console.log('name property is missing');
}

Hope this little info saves you from hours of frustration and headache as a JavaScript developer.

Make a Comment