What is Short-Circuiting of Logical Operators?

The logical operators (&& and ||) will convert their left-hand value to a Boolean type. It then decides what to return.

It can either return the original left-hand value or the right-hand value.

The or operator (||) will return the left value if it’s converted to true and it will return the value on the right if the left isn’t true.

How does the or operator (||) work?

Here’s an example:

console.log(null || "pick b");
//pick b

Starting here, the null value ends up being false, and because this is the or operator, it moves on to the next value which is pick b.

console.log("pick a" || "pick b");
//pick a

Here, you can see that during the evaluation from left to right, the “pick a” value evaluates as true and is returned.

You can use these operators to define a default value.

If you don’t know whether or not a value is empty, you can try setting it as the left value of an or operator. Then if that left value is false, the right value will return.

What values are always false in JavaScript?

The values that are always false in JavaScript are:

  • 0
  • NaN
  • “”

So if you see one of these values used on either side of the or operator, then the results will often be the value on the other side.

How does the and operator (&&) work?

When the left value of the and operator is false, then it returns the right value.

What is short-circuiting of logical operators?

Something you should really understand about logical operators like these two (&& and ||) are that the right value is only evaluated when necessary.

console.log(true || -23);
//true

Here, it doesn’t even evaluate the -23 because the answer is true. That’s it. It stops there.

console.log(false && pick b);
//false

Here, it’s false and that’s that.

Basically, this means that if the left side is true, then it will “short-circuit” and halt the evaluation of the right value because there’s no need.

This is known as short-circuit evaluation.

Conditional operators also follow short-circuiting rules

The conditional operators work the same way. When you have the second and third values, only the one that’s selected is evaulated.

Leave a Comment