DEV Community

Cover image for Write beautiful and Elegant Javascript code with short-circuit evaluation.
Horace FAYOMI
Horace FAYOMI

Posted on • Updated on • Originally published at Medium

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.

Top comments (13)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Your short example will also give the length of a string, or any other object that has a length property... so strictly speaking, the code is not equivalent at all.

Also, a shorter way to do the same thing (as the second example) would be:

let length = ~~arr?.length
Enter fullscreen mode Exit fullscreen mode
Collapse
 
fayomihorace profile image
Horace FAYOMI

Indeed it will give the length of a string. Even if a string behave like an array of characthers, it is not really an array as Array.isArray() will return false.
So yes the two code are not striclty equivalent. But it will do the job in a short and more elegant way.
And the way you showed is really nice, thanks.

Collapse
 
frankwisniewski profile image
Frank Wisniewski • Edited

your first sample must be changed to:

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

the following code:

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

is nice to look at, but not to be used in a team. The detailed version is much clearer and even years later it is immediately clear to every reader what is meant.

Collapse
 
fayomihorace profile image
Horace FAYOMI • Edited

indeed, the first version might be more readable as simple code (even if take more lines) is most of the times better code to read.
In my case I use it because it allows me to do the job (getting the length wihout exception) without needing each time to import and call a custom helper function that will do the job instead for reusability purposes.

Collapse
 
pengeszikra profile image
Peter Vivo
const length = Array.isArray(arr) ? arr.length : 0;

// or 

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

Maybe the first is sort enough and give back result 0 for string too.

Collapse
 
boredcity profile image
boredcity
const length = arr?.length ?? 0;
Enter fullscreen mode Exit fullscreen mode

is the way to go. why create an empty array when you just want to get 0?

Collapse
 
fayomihorace profile image
Horace FAYOMI

Indeed, this is better, thanks.

Collapse
 
fayomihorace profile image
Horace FAYOMI

Indeed ternary expression are another way to write short and beautiful code.
I'll cover it in another article.

Collapse
 
akshay9677 profile image
Akshay Kannan

Another interesting short hand expression I would like to add is the following,

Instead of doing this,

if(id === 1 || id === 2 || id === 3 || id === 4){
// 
}
Enter fullscreen mode Exit fullscreen mode

We can do something like this,

if([1,2,3,4].includes(id)){
// 
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
fayomihorace profile image
Horace FAYOMI

Indeed, nice one.

Collapse
 
koladev profile image
Mangabo Kolawole

Great article! We can discuss the readability surely but JavaScript is vast and these shortcuts make coding easier and modern.

Definitely worth checking the docs time from time!🚀

Collapse
 
ooling profile image
Sam oo Líng

just know those 3 logical ops can be used for "short 'if'" statement.
thanks for sharing!

Collapse
 
fayomihorace profile image
Horace FAYOMI

You're welcome.