Optional Chaining in JavaScript

Optional Chaining in JavaScript

Introduction

It is possible to read the value of a property deep into a chain of related objects by using the optional chaining operator (?.), which eliminates the need to explicitly verify the validity of each reference in the chain.

In the case of optional chaining, undefined is returned right away if a certain property is missing. In other words, if the value before ?. is undefined or null, it essentially stops the evaluation and returns undefined.

It is similar to the chaining operator (.), however, with the ?. operator, the expression short-circuits with a return result of undefined if a reference is nullish (null or undefined), as opposed to throwing an error.

Examples

Let's look at some illustrations.

let user;
console.log(user.name);
// Uncaught TypeError: Cannot read properties of undefined (reading 'name')

Here, we have declared the user object but not initialized it, and hence we got an error.

let user;
console.log(user?.name)
// undefined

Here, instead of throwing an error, the expression with the optional chaining operator just shows undefined.

let prop = user.firstName?.lastName;

JavaScript understands to implicitly verify that the user.firstName exists by utilizing the ?. operator rather than just .. When attempting to access the user.firstName, make sure that it is not null or undefined. The expression automatically short-circuits and returns undefined if user.firstName is null or undefined.

Instances of Optional Chaining

  1. It shouldn't be used on the left side of the assignment operator (=).

let welcome = {};
welcome?.message = "Hello";
// Uncaught SyntaxError: Invalid left-hand side in assignment

The expression will throw an error if the ?. operator is used on the left side of the assignment operator since it cannot be used to assign values.

  1. The variable before the ?. operator must be declared.

let user;
console.log(user?.age)
// undefined
console.log(user1?.name)
// Uncaught ReferenceError: user1 is not defined

As user1 variable is not declared, the console threw an error rather than undefined. So, the variable must be declared before using ?. on it.

  1. It should be used for safe reading and deleting, but not for value assignment.

delete user?.name
// This will delete the name property from the object user.
let nameUser = user?.name
// This will read the value of name property of the user object.
user?.name = "Sweta";
// This is not possible and will throw an error.
// Uncaught SyntaxError: Invalid left-hand side in assignment

Various Forms of Optional Chaining Operator

The ?. operator has three syntax forms:

  1. obj?.prop - It will return the value of obj.prop if obj exists, otherwise returns undefined.

  2. obj?.[prop] - It will also return the value of obj[prop] or we can say obj.prop, if obj exists, otherwise undefined.

  3. obj?.method() - It will call obj.method(), if obj exists, otherwise returns undefined.

Conclusion

With JavaScript's optional chaining, we can access properties without first confirming whether the property is present in the object or not. It will return null or undefined rather than an error.