DEV Community

Cover image for ES2020 'optional chaining' by example
Phantom
Phantom

Posted on • Updated on • Originally published at youtu.be

ES2020 'optional chaining' by example

One of the most anticipated features of ES2020 is 'Optional Chaining'. To recognize its enrichment for the JavaScript developers you first have to understand what it improves. Imagine you make an HTTP request to a server to get a list of employees. In this example, I use the HTTP library 'axios' that makes an XHR request to the server. Since this is promised based I use async-await to make it more readable and wrap it into a try-catch-block.

const apiUrl = 'http://dummy.restapiexample.com/api/v1/employees';

async function fetchEmployees(url) {
  try {

    const response = await axios.get(url);
    const employees= await response.data;

    return employees;

  } catch (error) {
    console.error(error);
  }
}

fetchEmployees(apiUrl);

Let's assume that for some reason, the endpoint is flawed and you get an error. But the error is too generic and you want to have more details about it. Inside the catch-block, we take the error parameter and check with a conditional-statement, whether it has the response, the data and at long last the message property attached to it. And if it's the case we want to console log the message.

if (error.response && error.response.data && error.response.data.message) {
    console.log('Here is the message:', error.response.data.message);
}

Have a second look at the conditional. That looks so repetitive. This is were 'Optional Chaining' makes your coding sessions more comfortable. Instead of digging deeper into the target-property, we can just write it down quite alone but with one difference. Replace the dots in between the chained properties with a question mark followed by a dot. Now 'Optional Chaining' looks up the deeply nested-subproperty 'message' without writing all the references between it.

if (error?.response?.data?.message) {
    console.log('Here is the message:', error.response.data.message);
}

And what about function calls?

You can even use 'Optional Chaining' with function calls of course! Assume we have a Car-Class that has two methods: 'accelerate' and 'brake'. We create a new Car-Instance and let myCar accelerate.

class Car {
  accelerate() {
    return 'Brrr';
  }
  brake() {
    return 'Shhh';
  }
}

const myCar = new Car();

myCar.accelerate(); // 'Brrr'
myCar.brake(); // 'Shhh'

Now it would we neat to brake as well. We call the brake-method and stopping the car. But all of a sudden the brakes are dysfunctional and you cannot brake anymore. In our scenario, our application would crash and so would the car. But not with 'Optional Chaining'. Use the question mark before the dot to make use of it. Your application will not crash anymore but it console logs undefined. And what happens with the car is up to your imagination :-).

myCar.brake?.(); // 'undefined'

If you liked the post/video I'd appreciate to see you as a follower on my social media:
YouTube
Twitter
Facebook

Top comments (0)