Alone in San Francisco

Fausto was walking alone in San Francisco, down Mission, headed south, through Bernal Heights, Excelsior, Ingleside, Oceanview, Crocker Amazon, down over to the Cow Palace, the site of the infamous…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Easy Javascript Object TypeError Protection

If you are writing javascript, it’s safe to say you are working with objects on a regular basis (not to mention the fact that objects are a huge part of how javascript works, and javascript’s primitives like arrays, string, booleans, etc. get wrapped in objects when you call specific methods on them). Usually when I’m working with an object, it’s because I am handling data of some kind, like a local state object or a JSON object returned from an API call. When accessing objects, properties may be one, two, three or more levels deep in the structure. Here is an example object we’ll use for reference:

To access any property of this user object, you could simply do things like:

What happens when you try to access a property on the object that doesn’t exist?

Nothing too terrible right? If the property doesn’t exist on the object, undefined will be returned as the value. Now what happens if you try to access a property two, three, or more levels deep, where both levels don’t exist?

Bad things happen, horrible things, things you don’t want to see! The severity of what happens varies greatly depending on the context of where the attempt to access the property is happening. This type of error can be pretty bad because it often leads to infinite loops, frozen apps, bad data, or just silent failures that lead to who knows what down the line. There are some things we can do though to protect ourselves against nasty bugs like this. You may find it redundant or an unnecessary to add an extra step, but you’re really going to save yourself some time and headache in the long run by being proactive about accessing object properties safely.

A tried and true method for accessing nested object properties safely is to simply check for the existence of a property before trying to do anything with it. For example, you could use a simple if statement:

That’s it for this bit on object properties. Let me know what you think or if you have any questions in the comments.

Add a comment

Related posts:

Coin Toss

It was a year of dripping chaos. A flash. A burst. A dizzying whirl wrapped up in the stars. A dream caught by the wind and tugged like a balloon gasping for that bizarre taste called freedom. It was…