Write beautiful and Elegant Javascript code with short-circuit evaluation.

fayomihorace

Horace FAYOMI

Posted on April 10, 2022

Write beautiful and Elegant Javascript code with short-circuit evaluation.

Article posted using bloggu.io. Try it for free.

Imagine the scenario where you have a variable supposed to be an array and you want to get its length. But the variable could also be null or undefined for some reason that doesn’t depend on you.
If the variable is not an array, trying to access its length will raise an exception:

Uncaught TypeError: Cannot read properties of null (reading 'length').

A very nasty thing for our end users to see. As we are good devs, we know we should prevent unexpected exceptions to be raised. To fix this one we might first try to verify if the data supposed to be an array is really an array, before accessing its length. Like this:

let length = 0
if (Array.isArray(arr)) {
    length = arr.length
}
Enter fullscreen mode Exit fullscreen mode

And that is not bad. It's even the normal way to do it.

But look at this instead:

let length = (arr || []).length
Enter fullscreen mode Exit fullscreen mode

You agree with me, that is more beautiful, short and elegant. And that is short-circuit evaluation.

Note: We could also solve the issue with others javascript features like this:

let length = arr?.length ?? 0;
Enter fullscreen mode Exit fullscreen mode

But as the purpose of this is article is to talk about short-circuit evaluation let's consider the first solution.


Now let's dive into it.

We already know about logical operators in Javascript:

  • logical AND (&&)
  • logical OR (||)
  • logical NOT (!)

But we can use them to do some tricks:

Return the first expression evaluated to false

You can use &&.
Here are some examples:

50 && true && 1 && false // Return: false
1 && 0 // Return: 0
Enter fullscreen mode Exit fullscreen mode

If all expressions are evaluated to true then it returns the last expression:

5 && 6 && true && 100  // Return: 100
Enter fullscreen mode Exit fullscreen mode

Return the first expression evaluated to true

Then you can use ||.
Here are few examples:

0 || false || 10 // return: 10
Enter fullscreen mode Exit fullscreen mode

We can use it to display default value when trying to access attribute that might not exist, might be null or undefined.

So, instead of:

message = 'There is no information available'
if (website.data) {
    message = website.data
}
Enter fullscreen mode Exit fullscreen mode

we can do this:

message = website.data || "There is no information available"
Enter fullscreen mode Exit fullscreen mode

We are at the end. I hope you liked this article. Follows me for more tricks and tips about Javascript, Python, Django and React.

💖 💪 🙅 🚩
fayomihorace
Horace FAYOMI

Posted on April 10, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related