Skip to content

Instantly share code, notes, and snippets.

@kimhogeling
Last active February 26, 2018 22:31
Show Gist options
  • Save kimhogeling/f95482ba1bdc2091aa4b9c82ee4f2bbd to your computer and use it in GitHub Desktop.
Save kimhogeling/f95482ba1bdc2091aa4b9c82ee4f2bbd to your computer and use it in GitHub Desktop.
Why the optional chaining operator might be pretty damn useful for readable code

Coming soon to JavaScript: Optional Chaining Operator

This example is inspired by mpjme's Fun Fun Function Video Watch that! It's short fun and explained really well!

This gist, is for me and my colleagues as a reference.

Given: Optional properties in an object

const hero1 = { name: 'Superman', address: { city: 'Metropolis', zip: 12345 } }
const hero2 = { name: 'Aquaman', address: { city: 'Atlantis' } }
const hero3 = { name: 'Doodyman' }

We want to log the the zip codes:

console.log(hero1.address.zip) // 12345
console.log(hero2.address.zip) // undefined
console.log(hero3.address.zip) // <-- Uncaught TypeError: Cannot read property 'zip' of undefined

Hmm that exception breaks our code, so let's make the address and zip code optional!

Today's solution might be a nested logic expression:

console.log(hero3.address && hero3.address.zip) // undefined

That's robust, but also a bit ugly and a bit noisy!

Another today's solution might be a nested ternary:

console.log(
    hero3.address
    ? hero3.address.zip
      ? hero3.address.zip
      : undefined
    : undefined
) // undefined

That quickly got unreadable and way too noisy!

Now, let's use the future's Optional Chaining Operator solution:

console.log(hero3.address?.zip) // undefined

YES! Now that's readable!

So can we use this future's solution today? Yes we can! This is currently (february 2018) in EcmaScript's proposal stage 1 of 4, butt will very likely be implemented and so it is added to Babel, which we already use in our portals, widget and recomAD Backend. Hurrayzz!

Sidenote for Ruby devs: Don't confuse this with the convention of ending boolean returning methods with a questionmark.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment