Optional Chaining Operator (?.) - JavaScript

umerjaved178

umerjaved178

Posted on July 13, 2021

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)
Enter fullscreen mode Exit fullscreen mode
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 
Enter fullscreen mode Exit fullscreen mode

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?.()
Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode

4- Optional Chaining with Arrays

You can use optional chaining with array too while accessing its elements

let arrayItem = arr?.[42];
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
umerjaved178
umerjaved178

Posted on July 13, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related