Optional Chains hug my heart

Since I’m on a bit of a SuiteScript 2.1 kick these days, I thought I’d share another common pattern I use and love.

Often in SuiteScript, I find myself needing to build then pull data from deeply nested Object structures.

Take this real-world function from some error handling code I recently wrote for a Map/Reduce summarize stage. The function accepts an Error – which has been previously augmented with additional data from the reduce stage where the error occurred – from the summarize context, then generates a URL the user can click to investigate further. Before it can do that, it needs to make sure the Error has all the right pieces:

ImageEven reading it right now I’m annoyed with it. So many &&s! Luckily, the wonderful ECMAScript designers have added a lovely new optional chaining operator, which we can take advantage of in SuiteScript 2.1, that really helps condense this same check down into just the really important parts:


Instead of checking every single level of the Object structure individually, we can simply examine the entire chain using the ?. operator – as opposed to the plain old . operator. If any part of the chain is not defined, the expression will short-circuit and return undefined, which would then short-circuit our larger logical expression correctly, without any errors.

<3 ?.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Related posts

January 7, 2021

Anything I wrote today about business would both feel and be inadequate. I simply can’t arrive at the words to express how I feel in this moment. So instead, here are a few helpful ...

Read More

December 20, 2020

2020 was a hundred swift kicks to the shorts and one giant kick in the ass. If you’ve lost people you love, if you’ve gotten sick or hurt, if you’ve lost your job, if ...

Read More

December 16, 2020

“I’ve been meaning to learn SuiteScript, but it’s hard to find the time …”“We’re slammed, and I just don’t have the time …”“I haven’t made the time …” All are variations of a theme ...

Read More

December 14, 2020

Last week we looked at mimicking the functionality of a REST endpoint with its own module (e.g. retrieving a User, or a list of Users, refreshing a token, etc). For complex integrations that rely on a large ...

Read More