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 undefinedHmm 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) // undefinedThat'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
) // undefinedThat quickly got unreadable and way too noisy!
Now, let's use the future's Optional Chaining Operator solution:
console.log(hero3.address?.zip) // undefinedYES! 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.