JavaScript Fundamentals: Optional Chaining

What is optional chaining? why is optional chaining important? and how do we implement error handling for optional chaining?

JavaScript Fundamentals: Optional Chaining
JavaScript Fundamentals: Optional chaining

Optional chaining is a new feature in JavaScript that lets us safely access nested objects without having to check for the existence of each level.

Optional chaining is used to handle the situation where a key may or may not exist on an object. If the key does not exist, then the expression will return undefined instead of throwing an error.

Consider the following object:

const user = {
  id: 1,
  name: 'John',
  address: {
    street: 'Main Street',
    city: 'New York'
  }
}

In order to access the street property of the address, we would have to write the following:

const street = user.address.street;

However, what if the address property did not exist? We would get an error. With optional chaining, we can write the following:

const street = user?.address?.street;

If the address property exists, the street property will be accessed. If the address property does not exist, JavaScript will simply return undefined instead of throwing an error.

Where optional chaining can be used in JavaScript

Optional chaining can be used with any property, not just nested objects. For example, we can also use it to call methods:

user?.sayHi();

If the user object has a sayHi method, it will be called. Otherwise, nothing will happen.

Optional chaining is a great way to improve the safety of your code, and it can make working with nested objects much easier.

Why use optional chaining in JavaScript

Some benefits of using optional chaining in JavaScript include:

Reduced chance of getting undefined errors

Optional chaining can reduce the chance of getting undefined errors in JavaScript by providing a way to access deep data structures without having to check if each level exists.

Optional chaining is a feature of JavaScript that allows you to access properties of an object without having to first check if the object exists.

For example, let's say you have an object that contains a nested object:

const obj = {
  nestedObj: {
    prop: 'value'
  }
}

If you try to access the prop property without optional chaining, you will get an error if the nestedObj property does not exist:

console.log(obj.nestedObj.prop) // 'value'

console.log(obj.otherObj.prop) // Error: Cannot read property 'prop' of undefined

With optional chaining, you can safely access the prop property without having to first check if the nestedObj property exists:

console.log(obj?.nestedObj?.prop) // 'value'
console.log(obj?.otherObj?.prop) // undefined

Optional chaining can be used to access any property, no matter how deep it is nested:

console.log(obj?.nestedObj?.anotherNestedObj?.prop) // undefined

More concise code

Optional chaining can be used to simplify code that would otherwise require multiple nested if statements. For example, consider the following code:

var user = {
    id: 42,
    name: "John Doe",
    address: {
        street: "123 Main Street",
        city: "New York",
        state: "NY"
    }
};

var street = user.address.street;

if (user && user.address && user.address.street) {
    var street = user.address.street;
}

With optional chaining, the same code can be written more concisely:

var street = user.address?.street;

Easy to use with TypeScript and other typed languages


Optional chaining is a feature in TypeScript that allows you to access properties of an object only if they exist. This is particularly useful when working with objects that may have missing or undefined values.

Without optional chaining, you would have to check for the existence of each property before accessing it. This can be tedious and error-prone. With optional chaining, you can simply access the property and TypeScript will automatically check for its existence.

Optional chaining is also useful when working with APIs that return data that may be incomplete. For example, if you are fetching data from an API and some of the fields are optional, you can use optional chaining to safely access the data without having to check for the existence of each field.

Error handling for optional chaining in JavaScript

If you are using optional chaining, you can use a try/catch block to handle any errors that may occur.

What is a try catch?

Try catch blocks allow you to test for errors in your code. The try block contains the code that may cause an error. The catch block contains the code that will execute if an error occurs.

try { 
    const result = myObj?.someMethod(); 
    console.log(result); } catch (error) { 
        console.error(error); 
    }

There are a few reasons why it is important to implement error handling when using optional chaining:

  1. To avoid unexpected errors: If optional chaining is not handled properly, it can lead to unexpected errors in your code. For example, if you are trying to access a property of an object that does not exist, you will get an error.
  2. To improve code quality: By handling errors properly, you can improve the quality of your code. This is because you will be able to avoid situations where your code does not work as expected.
  3. To make your code more robust: By handling errors properly, you can make your code more robust. This means that your code will be less likely to break when unexpected situations occur.
💡
Want to check out my other stuff? See my link wall at Zipply.io.