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!!!!!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post