Sign up to receive SuiteScript examples and advice directly in your email inbox.

Optional Chains hug my heart

Created: October 13, 2020

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:

function toApplicationUrl (e) {
  if (!(e.cause && e.cause.programId && e.cause.applicationId)) {
    return ''
  }
  // ...
}

Even 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:

function toApplicationUrl (e) {
  if (!(e?.cause?.programId && e?.cause?.applicationId)) {
    return ''
  }
  // ...
}

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.

❤️ ?.