Optional Chaining Operator (?.) - JavaScript

Topics covered:
1- Intro
2- Optional Chaining with Functions
3- Optional Chaining with Expressions
4- Optional Chaining with Arrays
5- With Nullish Operator
1- Intro
Optional chaining operator ?. loves you to read the value of within objects / nested objects with safety.
?. is similar to . except if the property in a object does not exist while accessing, it will return undefined instead of error/ breaking the program. This means you can explore The object with the carefree mind whether the property exists or not, thus making your code more solid.
const person = {
    name: 'John',
    dog: {
        name: 'toto'
    }
}

const catName = person.cat.name  // error
const catName = person.cat?.name  // error-free line (undefined)
Safety handling with & without Optional Chaining
//without optional chaining 
const catName = person.cat ? person.cat.name : undefined 

//without optional chaining 
const catName = person.cat?.name
Handling safety in deeper objects destroys the code readability
2- Optional Chaining with function call
Wooaahh! You can also call function with the peace of mind while digging in objects
const person = {
    name: 'John',
    vehicle: {
        year: 2012,
        drive(){
            return "I am driving"
        }
    }
}

const catName = person.vehicle?.drive?.()
3- Optional Chaining with property accessors (bracket notation)
Optional chaining operator while accessing the object values using bracket
const person = {
    name: 'John',
    dog: {
        name: 'toto'
    }
}

const catName = person.['dog']?.['name']
4- Optional Chaining with Arrays
You can use optional chaining with array too while accessing its elements
let arrayItem = arr?.[42];
5- With Nullish Operator
You can set the default value instead of returning undefined
const person = {
    name: 'John',
    dog: {
        name: 'toto'
    }
}

const catName = person.cat?.name  ?? 'Maani'
console.log(catName) //Maani

38

This website collects cookies to deliver better user experience

Optional Chaining Operator (?.) - JavaScript