DEV Community

Cover image for How to use optional chaining in JavaScript ES2020?

Posted on • Originally published at

How to use optional chaining in JavaScript ES2020?

Why worry about undefined or null values when optional chaining can be used?

When something comes from the outside but you are not sure if it is defined or you just want to simplify the logic of your app use this solution. 🔽

Before we start, I would highly recommend you to check out the runnable examples for the solution on our website:
How to use optional chaining in JavaScript ES2020?

Let's start by briefly explaining how the optional chaining operator works.

ES2020 introduced ?. operator that gives the possibility to avoid testing if an object or property before ?. notation exists, returning undefined value if not. The operator can be used with variables, properties, objects, arrays, functions, etc.

The ?. operator is similar to the . chaining operator, except that instead of causing an error if a reference is null or undefined, the expression returns undefined value.

📝 Note:

The ?. optional chaining operator is supported in the latest Babel compiler and TypeScript by default.

Syntax looks following way:

Syntax Description
obj?.prop object property access
obj?.[expr] object property access with brackets
arr?.[index] array item access by index
func?.(args) function calling

Simple object example:

const user = {
  name: 'Kate',
  age: 25,

console.log(user?.name);             // Kate

// console.log(user.address.street)  // causes error
console.log(user.address?.street)    // undefined
Enter fullscreen mode Exit fullscreen mode

Various types examples:

// accepted: uninitialised, undefined or null

var obj;
var arr = undefined;
var func = null;

console.log(obj?.items);        // undefined
console.log(obj?.['name']);     // undefined
console.log(arr?.[10]);         // undefined
console.log(func?.('Hello!'));  // undefined
Enter fullscreen mode Exit fullscreen mode

You can run these examples here

If you found this solution useful let me know in the comment section or leave a reaction 💗🦄💾.
Thanks for reading and see you in the upcoming posts! 😊🔜

Write to us! ✉

If you have any problem to solve or questions that no one can answer related to a React or JavaScript topic, or you're looking for a mentoring write to us on -> Questions

You can also join our facebook group where we share coding tips and tricks with others! 🔥

Top comments (4)

sznroe profile image
Sujan Rai

Love the post man. Thanks

menaiala profile image
Menai Ala Eddine

Simple and easy explanation. Thank you.

kunalt96 profile image
Kunal Tiwari

I am using it a lot and this is the very important concept in js now. I really loved the article, Thanks for publishing it. It will really help the community

aalphaindia profile image
Pawan Pawar

Good one!!