DEV Community

Ray
Ray

Posted on

React Learning Note: Optional Chaining

Image description
As we can see, each book has reviews, one for GoodReads and the other for librarything. They have different review accounts.
So let's create a function that gives us the total reviews count for each book.

function getTotalReview(book) {
  const firstValue = book.reviews.goodreads.reviewsCount;
  const secondValue = book.reviews.librarything.reviewsCount;
  return firstValue + secondValue;
}

console.log(getTotalReview(book));
Enter fullscreen mode Exit fullscreen mode

That is quite easy to get right, so now we go find out book id 3

Image description
Book id 3 don't have 'librarything' reviews value, if we still use the function we write up that will return Error"undefined".
To avoid that error we could read reviews value optionally

function getTotalReview(book) {
  const firstValue = book.reviews.goodreads.reviewsCount;
  const secondValue = book.reviews.librarything?.reviewsCount;
  return firstValue + secondValue;
}

console.log(getTotalReview(book));
Enter fullscreen mode Exit fullscreen mode

This '?.reviewsCount' question mark is what we call "Optional Chain", it will pass the null or undefined value, even if it still shows 'NaN' as a result but we will not receive an Error message.

Remember the double question mark to set the default value?
Let's do this:

function getTotalReview(book) {
  const firstValue = book.reviews.goodreads.reviewsCount;
  const secondValue = book.reviews.librarything?.reviewsCount ?? 0;
  return firstValue + secondValue;
}

console.log(getTotalReview(book));
Enter fullscreen mode Exit fullscreen mode

Now the problem is solved, we set this undefined 'secondValue' to be '0', and we can still get the total count number as a result without any error or null value.

In summary, we can use Optional Channing to let JS not read undefined values and double question marks to set a default value to make sure the function is working well all the time.

Image description

Top comments (0)