JSByte: JavaScript Optional Chaining `?.` Explained - How it Works and When to Use it

What is optional chaining?
Optional chaining, represented by ?.
in JavaScript, is a new feature introduced in ES2020. It can be used to chain properties that may be null
or undefined
. The syntax is -
const propNeeded = obj?.prop1?.prop2?.someProp;
If either of those chained properties is null
or undefined
, JavaScript will return undefined
. What if we want to return something meaningful? We can do this -
const nullCoalescing = obj?.prop1?.prop2?.someProp ?? 'variable unavailable;
Use cases
Accessing potentially null or undefined properties of an object.
Getting results from a variable that may not be available yet.
Getting default values.
Accessing long chains of properties.
TL;DR
Use optional chaining ?. for objects or long chain properties that may be null or undefined. The syntax is as follows:
const propNeeded = obj?.prop1?.prop2?.someProp;
---
Shruti Kapoor