JAVASCRIPT-Optional Chaining (?.)

JAVASCRIPT-Optional Chaining (?.)

Overview

Optional chaining is a simple and short expression that we can use to access chained properties when there is a possibility that the reference might be missing. When execute, It takes the reference to its left and checks if it is nullish (undefinedor null), if nullish, the checks will hold and return undefined. Else the check will continue to execute the expected value. A snippet for code using the ternary operator and optional chaining operator is below :

Code using ternary operator

const person = { 
        name : "Rakesh" , 
        hobby : "playing football"
    };
const addressCity=person.address?person.address.city: undefined;
console.log(addressCity) // undefined

In the above example, we can see that address property wasn't defined in the person object, so undefined was executed. The similar operation can be performed with lesser code using optional chaining.

Code using optional chaining

const person={ 
        name : "Rakesh" , 
        hobby : "playing football"
    };
const addressCity=person.address?.city.
console.log(addressCity) // undefined

History

Optional chaining was introduced back in ES2020. As per TC39, it is found mentioning that It's currently at stage 4 of the proposal process and is prepared for inclusion in the final ECMAScript standard. Presently we can use it in our program, but it has been mentioned that older browsers may still require polyfill usage.

Definition

The optional chaining operator is denoted with (?.) symbol. As per MDN, it has been defined that optional chaining is used in accessing an object's property or calling a function. If the object accessed or function called using this operator is nullish , the expression short circuits and executes undefined instead of throwing an error. In simpler words, optional chaining allows us to access chained object properties with fewer lines of code.

const person={ 
        name : "Rakesh" ,
        address : {
            locality : "Kammanahalli",
            city : "Bangalore",
            state : "Karnataka"
        },
        hobby : "playing football",
        employed : true;
    };

In the example, we can see a person object with different properties such as name, address, hobby, and a boolean field employed. Let's say we want to access the value of city. We would have to check if the:

  • person object exists

  • address property exists

  • cityy property is present

We would have to do three checks, and the if statement would like like this:

if (person && person.address && person.address.city){
console.log(person.address.city); // Bangalore

With the chaining operator, the above code can be shortened as below

console.log(person?address?city); // Bangalore

Here, the Console checks if the address property exists in the object person or not, if not will return undefined. Since it's available it will again check for city property under address property, like earlier, will return undefined if not available. Since it is available, it will return Bangalore.

More Example

We can use optional chaining with arrays as well, below is an example :

const studentMarks = [90, 100, 84, 78, 65, 79, 56]
console.log(studentMarks?.[1]); // 100

First of all, here it checks if the array studentMarks exists, and if it does, it executes the second array element.

Optional Chaining + Nullish Coalescing

Optional chaining pairs well with Nullish coalescing operator to provide fallback values. (Nullish coalescing: It's is denoted by the symbol ??. In nullish coalescing, If the item to the left of ?? is nullish, the item to the right will be returned.)

We know that if any optional chaining check equates to a nullish value within the chain, it will return undefined. So we can use our nullish coalescing to respond to the undefined outcome and set an explicit fallback value.

const person={ 
        name : "Rakesh" ,
        address : {
            locality : "Kammanahalli",
            city : "Bangalore",
            state : "Karnataka"
        },
        hobby : "playing football",
        employed : true;
    };
console.log(person?.address?.city??"Not found") // Bangalore
console.log(person?.address?.city1??"Not found") // Not found

In the above example, in the first console, we can see object person with address property & city property exists so Bangalore was executed. In the second console, we can see object person with addressproperty exist but city1 property doesn't exist so it returns"Not found"

Browser Compatibility

Optional chaining is compatible with the above-listed and above-browser versions.

Conclusion

Optional chaining is a handy recent feature of JavaScript that lets us check for nullish values while accessing property values.

I hope this blog has helped you to clarify your doubt about optional chaining.
Happy coding!