Finding stock photos for these posts is really fun.

Fix Javascript’s Most Annoying Problem - With Lodash’s _.get

Javascript is an imperfect language. Oh no! The secret’s out! Well, you knew that. However, there’s one problem that particularly drives me up the wall - javascript’s inability to gracefully handle undefined object properties.

A lot of us have nested objects that look like this:

var user = {
_id: '507f1f77',
email: 'william.bratches@gmail.com',
profile: {
firstName: 'William',
lastName: 'Bratches',
birthDay: {
month: 7,
day: 2,
year: 1991,
}
}

And functions that look like this:

function logUserBirthday(user) {

if (user && user.profile && user.profile.birthDay) {
var bd = user.profile.birthDay;
// ES6 template literals below
console.log(`${bd.month}/${bd.day}/${bd.year}`)
}
}

Focus particularly on this if conditional:

if (user && user.profile && user.profile.birthDay) {

What is this for? Well, I only want to do something if a ‘birthDay’ exists. However, if we don’t explicitly check that the parent of ‘birthDay’ exists, the function will crash! If ‘profile’ is undefined, checking user.profile.birthDay won’t return undefined - it will halt the function entirely.

Not only is this annoying to write, but it becomes especially problematic in frameworks like Meteor, where reactive functions have a habit of running even when their inputs are undefined. To guard against this, I’ve had meteor files with these conditional checks in a dozen places.

The solution

Use lodash’s _.get - it’s an absolute gift from the gods of javascript.

var bd = _.get(user, 'profile.birthDay').

That’s it. If profile is undefined, it will return undefined.

But wait! There’s More! Order in the next five minutes, and not only will _.get handle these undefined properties for you, but it will also allow you to pass in a default fallback value!

var validUser = _.get(user, 'profile.signUpComplete', false);

If anything is undefined, validUser will be set to false. Incredibly useful for maintaining exception-free code, and potentially improving app security.

That’s it! Feel free to leave an offering to gods of javascript in the comments!