Optional chaining "?. " in Javascript

ยท

4 min read

Optional chaining "?. " in Javascript

Hi everyone ๐Ÿ‘‹ !! Hope you all are doing well. In this blog I am going to discuss what is optional chaining and why do we need it.

Optional Chaining operator was introduced in ES2020. It is also available in TypeScript, starting from version 3.7. It changed the way we can access properties in deep object nested structure.

Why do we need optional chaining?๐Ÿค”

When dealing with objects that has different set of properties for example , Here object user1 has full set of properties with name and last name as required properties and address as optional property but object user2 has only name and last name as their properties.

const user1 = {
          name: "John",
          lastName: "Doe",
          address: {
                      pin: 2134,
                      state: "Cardiff"
                  }

const user2 = {
          name: "Harry",
          lastName: "Potter",

Now if we want to access object user1 address property we will get the desired output but for object user2 we don't have optional address property so, what will happen? we will get undefined.

console.log(user1.address) // {pin: 2134, state: "Cardiff"}
console.log(user2.address)// undefined

Further, if we want to access nested pin property of address for object user1 we will get the pin 2134 but for object user2 we will encounter an type error of TypeError: Cannot read properties of undefined (reading 'pin')

console.log(user1.address.pin) // 2134

console.log(user2.address.pin) //TypeError: Cannot read properties of undefined (reading 'pin')

So, in order to access these objects and to work on them, we also need to handle some scenarios like we don't want the object to be null or undefined, the properties that we need to access should be available, etc. So to handle this kind of scenario we can use if-else or multiple && operations to avoid any error or code failure.

const result= user1 && user1.Address && user1.Address.pin
if(result){
  console.log(result)
}else{
  console.log("no property")
}
//2134

const result= user2 && user2.Address && user2.Address.pin
if(result){
  console.log(result)
}else{
  console.log("no property")
}
//no property (as result will be undefined)

But we can see there is a lot of code , more properties are being nested more complex to access them , it would be great if we can avoid it .This is where we need the optional chaining operator.

console.log(user1.address?.pin)//2134

console.log(user2.address?.pin)//undefined

Here in case of object user2 as address is missing user2.address?.pin evaluates to undefined and it prevents from throwing the type error TypeError: Cannot read properties of undefined (reading 'pin') and in case of object user1 it prints the desired output of pin.

What is optional chaining (?.) operator ?

We have come to know optional chaining operator provides a simpler way of accessing nested object properties even if an intermediate property doesnโ€™t exist. The optional chaining ?. stops the evaluation if the value before ?. is undefined or null and returns undefined.

When to use optional chaining?

We should resist overuse of optional chaining to access any kind of property that would lead to misguided usage .It should be used when the nearer properties might be nullish . Here in case of our code logic to use (?.) optional operator user1?.address is useless as the user1 is not going to be nullish.

Short Circuiting evaluation

Another interesting fact of optional chaining is if we encounter nullish value on the left-hand side the evaluation of the right-hand side accessor stops. Here in the example as nullObject holds a nullish value, the optional operator evaluated to undefined and skips the evaluation on the right-side accessors, and hence "x" is not incremented.

let nullObject = null;
let x = 1;
let prop = nullObject?.[x++];
console.log(x); //1

Different types of Optional Chaining

  • object?.property : It is used to access a static property , returns object.property if object exists otherwise undefined.

  • object?.[property] : It is used to access a dynamic property or array , returns object[property] if object exists otherwise undefined.

  • object.method?.(args) : It is used to execute a object method , returns object.(method) if object.method exists otherwise undefined.

This comes to the end of the blog. Hope you folks find it useful. Any suggestions or anything to add I would love to hear it in the comments below.Thank youโœจ !!

๐Ÿ‘‰Connect with me: Linkedin Twitter

ย