DEV Community

Ray
Ray

Posted on

React learning note: Logical Operators

Hello, everyone! Sorry for stopping updating for a couple of weeks while I was busy with finals a while back, I'll try to get back to a weekly update as often as I can later on. In the meantime, I've been offered a summer internship at BOPRC, so if I gain any new understandings during the internship, I'll be blogging about them as well~!

Back to our React study notes. Logical Operators are used quite frequently in React programming.
The 'end Operator' and 'or Operator' have a feature called: short-circuiting, short-circuiting In logical Operators, in certain conditions the operator will return the first value.

'end Operator'

console.log(false && "hello");
console.log(true && "hello");
Enter fullscreen mode Exit fullscreen mode

'hasMovieAdaptation' is the variable we defined earlier, and we can also use it as an end operator, more like 'if'.
Image description

This syntax also applies to truthy and falsy Values, eg:
Image description

'or Operator'
The 'or operator' is the inverse case and returns the first upper end as long as it is true

Image description

We can use this feature to define default values for specific data. For example:
A book with an ID of 2 has no Spanish translation
Image description
Also works for undefined values
Image description
There is also a notation: nullish coalescing operator, which works much like 'or operator', but it does also short circuit or falsy value

const count = book.reviews.librarything.rating.reviewsCount ?? "No data here";
count;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)