How to use Optional Chaining in LWC

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.

💡
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