Salesforce Interview Questions & Answers Book is now available!

Grab Now

LWC

How to use Optional Chaining in LWC

Optional Chaining in LWC is considered one of the best practices. It is a lot more verbose, and easy on the eyes.

By Teja, ex-Salesforce engineer · Updated February 12, 2024 · 1 min read

It's quite common in LWC to work with objects.

Whenever we need to work with data in JavaScript there is a 90% possibility is there it is going to be either an Object or an Array.

Let's narrow the scope of this blog post on Objects.

When we invoke an Apex method or when we make a REST API call using fetch API directly from LWC what we get back is going to be an Object or Array of Objects.

Tip

Did you know that you can use fetch API in LWC? If No, check this out!

It's a mandate in JavaScript to do proper null checks to avoid awkward undefined errors.

As a part of it, we do something as shown below.

let result = {
  data: {
    value : '001'
  }
}

if(result && result.data && result.data.value ){
  let recId = result.data.value;
}

doing null check using the old-fashioned way

However, it is suggested to get rid of the legacy approach and start using Optional Chaining.

It is a great tool to handle null checks in Objects.

The above code can be refactored to something like this.

let result = {
  data: {
    value : '001'
  }
}

if(result?.data?.value){
  let recId = result.data.value;
}

doing null check using optional chaining

You can see that this approach is a lot more verbose, easy on the eyes, and clean.

Hope this is helpful

Learn it by building it

Every course, every code repository, the discussion group and certificates of completion — one subscription.

Keep me in the loop!

Email me when a new episode is published (promise, I will not spam you)

You're signing up to receive emails from Salesforce Casts