Short-circuiting in Javascript

Short-circuiting in Javascript

Logical operators in Javascript are used to combine two boolean values. But there are many more things that we can do with them, especially with the AND and the OR operator. One of those things is known as short-circuiting.

In this article, we will learn about short-circuiting and use cases for it.

What is Short-circuiting?

According to Wikipedia,

It is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression.

Breaking down that definition, we have that short-circuiting evaluates two arguments. The second argument is evaluated only if the first argument doesn't meet the condition to determine the result. Meaning that if the first argument meets the condition, then we won't get to the second argument, and the expression will return that first argument, in which case we say the expression is short-circuited.

Short-circuiting with the AND (&&) operator

This operator will return false as soon as it gets any falsy value and will return the last true value if all the values are true.


true && true
// true
true && false
// false
false && false
// false

Let's say we have a scenario where we have a code logic that checks whether a user included '@' when submitting an e-mail input, and if they did, then we should send an HTTP request. You can find an example below:


if(input.trim().includes('@')){
  sendRequest();
}

But we can also write the above code like the code below, and the code will work the same way:


input.trim().includes('@') && sendRequest();

The above code will work because the AND operator will evaluate the code from left to right and return true if both operands are true.

It won’t work:

  • If the first operand is false. That’s because the entire argument immediately short-circuits and is rendered false.
  • If the second operand is false. And that’s because the expression is rendered false if any operand returns false when using theAND operator.

It means that for the second operand to be looked at by Javascript, the first must be true and only then can the second operand be evaluated.

And it also means that the second operand must return true, else the request in our example won’t be sent.

From the example above, it means that if we trim our input and it doesn't include '@', then the expression will immediately short-circuit, and we won't even get to the part where we send our request.

Other examples include:


const age =  25;
function driveCar() {
  return 'Driving Car';
}
const result = age > 18 && driveCar();
console.log(result);
// Driving Car

The operator checked if age is greater than 18 and since that condition was true, the next condition was checked and since that one was also true then it returned the last truthy value

Note: It is important to note that if faced with a scenario like the one above in which we sent an HTTP request after checking e-mail input, then it's better to use an if statement or ternary operator as the case may be. However, it's essential to understand that they are doing the same thing.

Short-circuiting with the OR ( || ) operator

This operator will return true as soon as it gets any truthy value and will return the last false value if all the values are false.


true || true;
// true
true || false;
// true
false || false;
// false
false || true;
// true

It means that when Javascript evaluates an OR expression, and the first operand is true, then Javascript will immediately short-circuit and won't even look at the other operand. It will keep going if it encounters a false value until it gets a true value. If there is no true value then it returns the last false value.

In the code block below, we have #### representing any value we want to give it, but that won't matter because Javascript won't look at that and immediately return the true value.


true || ####
// true

Let's take a practical example below:


const a;
const b = 'Isaac';
const c = 'Javascript won't look at this';
const myName = a || b || c;
console.log(myName);
// Isaac

In the code block above, a is undefined, and Javascript moves onto b, the next operand. Since that is a truthy value, it immediately stores its value in myName and then short-circuits without looking at the other operand.

Using AND (&&) and OR ( || ) together

You can create chains of command and shorten the length of your code by combining the powers of both operators, as we will see in the code block below:


const height = 6; // in feet

// Using an if/else block
if(height >= 6){
  action = 'Play Basketball'
} else{
  action = 'Can't Play Basketball'
}
console.log(action); // Play Basketball

// Short-circuiting
const greeting = (height >= 6 && 'Play Basketball') || "Can't Play Basketball";
console.log(greeting); // Play Basketball

In the code block above, our condition was evaluated by Javascript, and the AND block returned true. It then continued evaluating, and since the first condition was true, it means we could rewrite the as you will see in the example below:


const greeting = height >= 6;
true || "Can't Play Basketball"

And since OR immediately short-circuits at first sight of true, it means that the other operand won't be looked at, and that's the reason we get (Play Basketball) when we console-logged our greeting. I'm sure with the example above, we can see the power of short-circuiting in effect as it helped us shorten our code and create chains of command when used appropriately.

Conclusion

In this article, we looked at logical OR and logical AND, their meaning, their use-cases, how they can be used separately and combined. I hope you incorporate and truly understand short-circuiting in Javascript as it will also make your life easier in Javascript and when you pick up a Javascript framework especially React.