Optional chaining in JavaScript

Optional chaining in JavaScript

Introduction

In javascript's ECMAScript 2020 update, a new feature called optional chaining was added. Optional Chaining allows developers to access nested properties of an object without worrying about whether or not intermediate properties exist. In other words, it allows you to check if an object has a specific property and, if so, access its value without raising an error. The implementation and operation of optional chaining are covered in more detail in this blog post.

As programmers, we frequently work with complex data structures that contain multiple levels of nested objects and arrays. In such circumstances, it is very challenging to access a property buried deep within the nested structure, and in some situations, it may result in a TypeError that the property is not defined.

Accessing the property of the nested object

Traditional method :

Before optional chaining, let's first explore how developers access nested properties in traditional method by using the example below. The names of all the properties in a nested object must be chained together to access a property using JavaScript's traditional dot (.) operator.

consider the following object :

const student={
  name:"John",
  stream:{
    science:{
      dept: "comp.sc",
      roll_no: 12
    }
  }
}

If we want to gain access to the student's department, we would like the following.

console.log(student.stream.science.dept);//comp.sc

What if the stream property is not defined, is null, or is undefined? We would get an error:

console.log(student.stream.science.dept);//Uncaught TypeError:Cannot read property 'stream' of undefined

To avoid this error, use a series of conditional statements to determine whether each intermediate property exists:

if (student && student.stream && student.stream.science && student.stream.science.dept) {
  console.log(student.stream.science.dept)//comp.sc
}

This method is effective, but as the number of nested properties grows, it can easily become difficult and lengthy. Optional chaining is essential in overcoming these challenges.

Optional chaining :

Optional chaining is represented by a question mark (?) placed just before the dot in dot notation. Here is the syntax for this :

object?.property

The ?. operator determines whether the object exists and is not null or undefined. If the object exists, the property is accessed normally. If the object is null or undefined, the expression will returns undefined rather than throwing an error.

Let's consider the same example with optional chaining :

console.log(student.stream.science?.dept); //comp.sc

What if the stream property is not defined, is null, or is undefined? It will give undefined without throwing an error

console.log(student.stream?.science?.dept); //undefined

We can use multiple chaining together at a time like in the above example.

Optional chaining can be used with the following types in javascript such as

  • function call :

    Even if the function is null or undefined, we can call it safely using optional chaining.

    syntax:

      object?.functionName?.(arguments)
    
  • array elements and method :

    Even if an array is empty or undefined, it is possible to invoke functions and access its elements safely by using optional chaining. The value of the element or method is returned if it exists. Undefined is returned if the element or method does not exist, is null, or is undefined.

    syntax:

      arrayName?.[index]?.methodName?.(arguments)
    
  • nullish coalescing :

    In JavaScript, we can use optional chaining and nullish coalescing to give default values to expressions that might be null or undefined.

    syntax:

      objectName?.propertyName ?? defaultValue
    

Conclusion :

Chaining is a very powerful feature. It comes in handy when dealing with complex data structures. However, because this method is a new feature, it is not supported by all browsers.