DEV Community

sachinM
sachinM

Posted on

Conditional check of presence of an element with chaining

We many times fail to write a better conditional checks for JSON objects and fall-asick with either errors or more code.

Here is the better solution to avoid both of these issues!!!!

source : happyho.in

Introduction

Optional chaining is available for Node - 14.0.0 or higher versions. ( complete browser compatibility is here )

Usage

Let's say there's code for an object to select the organiser name from the object of event

We will find it something like this :

const organiser = event.organiser.name

And what if event or organiser is undefined for an error ?

Image source : seekpng

you'll endup with error : Cannot read the properties of undefined ( reading 'name' )

You may think and logic scarier then the bug and may fix it like this :

const organiser = (event && event.organiser && event.organiser.name) && event.organiser.name

Woooohhhh!!!! you resolved the bug!!!
But did you maintain the standards of code???

Nnnnnnnnoooooooooooooo!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

How about this ?

const organiser = event?.organiser?.name

Great!!!!!!

Image source : emojiterra

This will keep the code less as well as check the conditions of presence.
Returns undefined if any of the parameter in the chaining is undefined.

Hope this small thing makes your day and improves your code!!!!!

Top comments (0)