October 13, 2020

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:

Image

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

March 3, 2021

Does the physical location of a competent employee change the amount of value they can deliver for your organization? If it does, I’d be keen to hear your story. If it does not, why ...

Read More

March 2, 2021

Today a friend and former colleague of mine – who happens to now be in a development leadership role for a NetSuite partner – was lamenting the extreme difficulty of finding and hiring NetSuite ...

Read More

March 1, 2021

Software is never finished; clients are always changing and re-prioritizing. NetSuite is ever a moving target – always updating and evolving. Market forces are always shifting and shoving, forcing new demands on your business. ...

Read More