Tag Archives: object

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 user.name === '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

Accessing Values in Javascript JSON Objects with Keys containing Hyphens (Dashes) CodeUnit 12 AUG 2010

In Javascript, JSON objects (well, JS objects in general) have a great short hand little way of accessing values using the fullstop object notation.

In other words, using a JSON dataset looking like:

{“status”:”1″,”message-data”:”Success!”}

we could access the “status” value by simply entering:

alert(myobject.status);

However, if we tried the same thing with the “message-data” key, you will note that this will fall over syntactically straight away – all because of that silly hyphen (dash).

So the way around this?

Well you basically have to revert to the long notation format to get at the data associated with these keys, meaning that you would now need to do something like this:

alert(myobject[“message-data”]);

And now you know.

Nifty.