Select Page
Javascript optional chaining

Javascript optional chaining

2020 is a hell of a year for most of us but not with Javascript as it has introduced a lot of new cool features including one of my favorites: Optional Chaining.

If you haven’t tried Typescript before, this might be new to you but this functionality is very much used in Typescript. Let’s dive into the code, shall we?

Suppose you have the following code:

const human = { job: null }

What if you want to access a particular property of job like so:

const salary = human.job.salary

This code will throw an error telling us that it can’t read salary of null. Typically devs will use ternary operator to avoid the error like so:

const salary = human.job ? human.job.salary : undefined

While this will work the code will be easily repetitive when you are trying to read lots of properties from a huge object that might or might not exist. Thanks for Javascript, you can now do it elegantly in your code like so:

const salary = human.job?.salary

The code will not produce an error. If the job property happened to not exist, then it will just return an undefined.

So where’s the chaining part? Suppose human might or might not exist then your code can look as following:

const salary = human?.job?.salary // outputs undefined

That’s it for Optional Chaining.  2020 for Javscript have been awesome there are other of cool stuffs that have been introduced like Object.fromEntries, matchAll(), dynamic import,  Promise.allSettled, Null Coalescing and others.

Let’s keep rockin with Javascript!

Javascript optional chaining

TF is noop and what’s the use of it (JS)?

Have you encountered a function or a variable that is called noop in any source code you are reading? Have you asked yourself what the hell is that for?

Well, noop just means NO OPERATION. Meaning do not do something, return undefined or return an empty function. It is literally simple as that.

So what is the need for this noop at all?

Backup callback / Legacy code

Supposed you have a function like that accepts a function like so:

function displayInfo(callbackFn) {
  // execute callbackFn and and perform other complex things

and supposed your code will run in different environments like desktop, web, and mobile.

Now you need to provide displayInfo() a valid callback function that might only be available for a particular environment. Typically developers will create an empty function that will do nothing, thus noop. Like so:

 const callbackFn = environmentFn ? environmentFn : () => {} 

But writing an empty function every time you need it is not good in the eyes right? As such, developers separate it on a separate function like so:

const noop = () => {} 

That’s it! If ever you think of another usage of the noop function feel free to comment it below.