I’m always forgetting how to to this in Javascript – here’s a couple of ways of validating if an object is undefined or null, and the good points about using them.
Suppressing undefined errors completely
if(typeof(obj) === ‘undefined’ || obj === null ) {
// “obj” doesn’t exist!
}
This method should hide all errors relating to missing objects. Good if you want to prevent errors showing to the end user, but this method won’t make it easy for you to spot Javascript errors without additional logging. I often use the above code when handling values from external JSON where I can’t always trust the data the user will receive.
Throwing errors for undefined but not null
if (obj == null) {
// “obj” doesn’t exist.
}
The above it simpler than the first, but the above should throw a ReferenceError if the object is undefined. This is useful for spotting issues in general Javascript programming, but may cause issues when handling JSON that’s out of your control.
Checking if a Javascript object has a property
if(!obj.hasOwnProperty(“<property name>”)){
// Property doesn’t exist!
}
This will check to see if a JS Object contains a property. This is especially useful with handling JSON, and is better than the first code block above.