Published on

Create Elegant Javascript Code Using Short-Circuit Evaluation

featured Image

Consider the following scenario: you have a variable that is intended to be an array and you want to know its length. However, the variable might be null or undefined for reasons beyond your control. If the variable is not an array, attempting to access its length will result in the following exception:

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

This is a really bad thing for our end consumers to view. As excellent developers, we understand the importance of avoiding unexpected exceptions. 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. As an example:

let length = 0
if (Array.isArray(arr)) {
    length = arr.length

That is not a terrible thing. It's even the standard procedure.

But consider this instead:

let length = (arr || []).length 

You agree with me that it is more attractive, concise, and elegant. And that, my friends, is short-circuit testing.

Now let's get started.

In Javascript, we already know about logical operators:

  • AND it is rational (&&)

  • (||) logical OR

  • NOT rational (!)

However, we may utilise them to perform several tricks:

Return the first expression that was evaluated as false. && can be used. Following are some examples:

50 && true && 1 && false // Return: false
1 && 0 // Return: 0

If all of the conditions are true, it yields the last expression:

5 && 6 && true && 100  // Return: 100

Return the first expression that was evaluated as true.

Then you can use ||.

Following are a few examples:

0 || false || 10 // return: 10

We may use it to show the default value when attempting to access an attribute that may not exist, be null, or be undefined.

As an example, instead of:

message = 'There is no information available'
if (website.data) {
    message = website.data

This is something we can do:

message = website.data || "There is no information available"

We've reached the end of the road. I hope you found this information interesting. Follow me for more Javascript, Python, Django, and React techniques and tips.