Understand the Superpower of Optional Chaining in JavaScript

Learn how to use upcoming JavaScript feature Optional chaining

?.Optional Chaining operator

Image from twitter by Daniel Rosenwasser (@Daniel Rosenwasser).

Optional Chaining

Optional chaining will eliminate the need for manually checking if a property is available in an object . With optional chaining the checking will be done internally .

Example without Optional chaining.

Consider the above function , that will print the hi message with user name

When we pass an user object which doesn’t have the name property

To solve the above problem what we do is , we will add check if name property available in the user object

Using Optional Chaining

The optional chaining will check if an object left to the operator is valid (not null and undefined). If the property is valid then it executes the right side part of the operator otherwise return undefined

Basic Example

The native JavaScript equivalent code for above optional chaining operator is

Using variables as property name

We can use variables as property name in optional chaining

Function call with optional chaining

You can use optional chaining to call a method which may not exist.

Referemce : MDN.

Follow Javascript Jeep🚙💨.

JavaScript in Plain English

Learn the web's most important programming language.

Javascript Jeep🚙💨

Written by

Articles related to javascript

JavaScript in Plain English

Learn the web's most important programming language.

More From Medium

More from JavaScript in Plain English

More from JavaScript in Plain English

7 really good reasons not to use TypeScript

More from JavaScript in Plain English

More from JavaScript in Plain English

Why you should learn React instead of Vue

More from JavaScript in Plain English

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade