loading...
Cover image for Optional Chaining

Optional Chaining

bhagatparwinder profile image Parwinder πŸ‘¨πŸ»β€πŸ’» ・3 min read

JavaScript with Parwinder (41 Part Series)

1) What is Javascript? 2) Where can I run JavaScript? 3 ... 39 3) Types in JavaScript 4) What are objects in JavaScript? 5) Reference vs Value 6) Arrays in JavaScript 7) Array Methods in JS 8) Array Instance Methods 9) Array Instance Methods II 10) Functions in JavaScript 11) Type of Functions in JavaScript 12) Scope in JavaScript 13) Hoisting in JavaScript 14) Closures in JavaScript 15) Debugging in JavaScript: Console Methods 16) The new Keyword in JavaScript 17) JavaScript: Type Conversion 18) JavaScript: While Loop 19) JavaScript: Do While Loop 20) JavaScript: For Loop 21) Lesser-Known JavaScript Tricks 22) Events & Event Handling 23) Event Bubbling 24) Event Capturing 25) JS: Switch Statement Explained 26) Arrow Function: Basics 27) this Keyword in JavaScript 28) Arrow functions & this keyword 29) Callback Functions & Callback Hell 30) Strict Mode in JavaScript 31) Optional Chaining 32) Timers & Intervals 33) Arrow Function and The new, arguments & super Keyword! 34) Promises: Introduction 35) Promises: Chaining, Error Handling & Operators 36) New Promise Methods: allSettled & any 37) Async/Await: Introduction 38) Async/Await: Common Mistakes 39) Async/Await: Error Handling 40) Truly Understand Bind, Call & Apply 41) Destructuring Arrays

Introduction

🚨 Before you proceed, keep in mind that optional chaining is not in the release on ECMAScript (yet). TC39 has it in stage 4 (Finished). You might need a polyfill for it.

Accessing object properties is a common occurrence in JavaScript. Plenty of times, these properties are nested. When you access a property on an object where the object is missing, JavaScript throws an error.

Let's go through some examples to understand it.

const myObject = {
    name: "Parwinder",
    car: "Cybertruck",
    age: 42,
    computers: {
        first: {
            name: "iMac",
            year: 2017,
            spec: {
                cpu: "i7",
                ram: "16GB"
            }
        },
        second: {
            name: "MacBook Pro"
        }
    }
}

console.log(myObject.computers.first.spec.cpu); // i7
console.log(myObject.computers.second.spec.cpu); // Cannot read property 'cpu' of undefined

The first log goes through the object to get the CPU for my first computer. When you try doing the same for the second one, an error occurs.

We are trying to access the property cpu of spec when spec doesn't even exist. cpu is on the fifth levelβ€”anything before it can be null or undefined (myObject, computers, second, or spec).

We solve this problem by using if statement combined with AND && operator.

if(myObject && myObject.computers && myObject.computers.second && myObject.computers.second.spec) {
    console.log(myObject.computers.second.spec.cpu);
}

While the above script works, it is not the cleanest looking code. It's a lot of code to write to check for null/undefined of a property chain. Enter optional chaining.

Optional chaining is represented by ?. and it can be used for keys and expressions on objects, array indexes, and functions available in an object.

Optional chaining with object properties

We can rewrite the above if statement like below using optional chaining:

myObject?.computers?.second?.spec?.cpu // undefined

// Concise and easy to read code
// or

myObject.computers.second.spec?.cpu

The ?. operator short circuits an object property evaluation. Instead of returning an error by keeping on evaluating, optional chaining terminates as soon as it finds the first undefined/null in the chain and returns undefined.

?. only works where it is placed.

In myObject.computers.second.spec?.cpu the first three properties have to be present. Only spec is using optional chaining operator, and if spec does not exist, it will return undefined.

For any of the first three properties, an absence of the property will result in an error. So use ?. only where something is optional and may be present or not. Using it everywhere could result in your code silently failing and harder to debug.

Example: If computers is optional, but myObject is mandatory, always opt got

myObject.computers?.

and not

myObject?.computers?.

Optional chaining with object expressions

We can still use optional chaining if we use the literal or square bracket notation for accessing properties.

console.log(myObject.computers.second?.["spec"].cpu); // undefined
console.log(myObject.computers.first?.["spec"].cpu); // i7

Optional chaining with functions

Let us add a function to our object.

const myObject = {
    name: "Parwinder",
    car: "Cybertruck",
    age: 42,
    getAge: function () {
        return this.age;
    }
}

console.log(myObject.getAge()); // 42

If the function could be optional, we can opt-in for optional chaining.

console.log(myObject.getAge?.());

Optional chaining would ensure JavaScript does try to execute a function that does not exist. The invocation never happens due to the short circuit provided by ?. operator.

Optional chaining with arrays

const names = ["Parwinder", "Lauren", "Leah", "Robert", "Eliu"];
console.log(names[3]); // Robert

const newEmployee = names?.[3]; // Check if names exists
console.log(newEmployee); // Robert

🚨 Optional chaining does not work on the left-hand side of an assignment.

let myObject = {};
myObject?.name = "Parwinder"; // Uncaught SyntaxError

JavaScript with Parwinder (41 Part Series)

1) What is Javascript? 2) Where can I run JavaScript? 3 ... 39 3) Types in JavaScript 4) What are objects in JavaScript? 5) Reference vs Value 6) Arrays in JavaScript 7) Array Methods in JS 8) Array Instance Methods 9) Array Instance Methods II 10) Functions in JavaScript 11) Type of Functions in JavaScript 12) Scope in JavaScript 13) Hoisting in JavaScript 14) Closures in JavaScript 15) Debugging in JavaScript: Console Methods 16) The new Keyword in JavaScript 17) JavaScript: Type Conversion 18) JavaScript: While Loop 19) JavaScript: Do While Loop 20) JavaScript: For Loop 21) Lesser-Known JavaScript Tricks 22) Events & Event Handling 23) Event Bubbling 24) Event Capturing 25) JS: Switch Statement Explained 26) Arrow Function: Basics 27) this Keyword in JavaScript 28) Arrow functions & this keyword 29) Callback Functions & Callback Hell 30) Strict Mode in JavaScript 31) Optional Chaining 32) Timers & Intervals 33) Arrow Function and The new, arguments & super Keyword! 34) Promises: Introduction 35) Promises: Chaining, Error Handling & Operators 36) New Promise Methods: allSettled & any 37) Async/Await: Introduction 38) Async/Await: Common Mistakes 39) Async/Await: Error Handling 40) Truly Understand Bind, Call & Apply 41) Destructuring Arrays

Posted on by:

bhagatparwinder profile

Parwinder πŸ‘¨πŸ»β€πŸ’»

@bhagatparwinder

Happy, cheerful, confident. Web developer based out of Chicago :)

Discussion

markdown guide