Avoid ‘&&’ with optional chaining ‘?.’ in Javascript

Rajesh Lousigam
2 min readJan 27, 2021

--

Photo by Lola Russian from Pexels

The new ES2020 added a whole lot of things that can make developer life easier and also their code very clean.

Often as a javascript front-end developer, I faced the issue of accessing value inside a deeply nested object.

For example, if I have a JSON response from API like

{
data:{
name: 'ABC,
info:{
id:'123',
details: '',
}
}
}

Now, Suppose the API can return the value of info as empty or null, and

If I was to read the value of id,

I would just use the dot(.) operator to get access like so

let id = data.info.id

But if the info property is not available, this would return an error since the property is not found.

In this case, before ES2020, I would normally use a library like lodash or mostly use the ‘&&’ operator like so

let id = data && data.info && data.info.id

This will work without any issue but look at my code, it does not look very professional and absolutely messy.

The ES2020 Optional Channing (?.) come to the rescue to avoid this kind of lengthy value and property check.

The ‘?.’ is very EASY and CONVENIENT to use. Just look at the changes made to the above code using Optional Channing.

let id = data?.info?.id

Amazing!! , just add the ‘?.’ operator in which you want to check for existence.

If the property exists, it will go through it,

If not it will short circuit and return undefine or null.

Happy coding everyone !!!

--

--

Rajesh Lousigam
Rajesh Lousigam

Written by Rajesh Lousigam

Founder of Lousigam Labs | SDE @ StepOut

No responses yet