Short-circuiting in logical operators, visualized

ProgrammingJun 2021

The logical operators && (and) and || (or) run on what can be called short-circuit logic. Simply put, that  means that expressions will only be evaluated if the expression preceding it is not enough to determine the truthiness of the logical expression.

In the example below, all three expressions need to be true for the entire logical expression to be true. But given that 7 isn’t bigger than 8, the last logical expression, a simple true expression, doesn’t need to be evaluated since all three are no longer true.

The same is true for the || (or) operator. Whereas the && (and) operator short-circuits if it finds a false statement, the || (or) operator short-circuits when it finds a true operator. Since all it needs is for one of the expressions to be true.

In the example below, undefined.length would crash the program and result in a TypeError. But in this logical expression, because the first argument is true, and only one expression needs to be true, the remaining is short-circuited, and not evaluated.Uses of short-circuiting

Uses of short-circuiting

Short-circuiting can be used as a replacement for simple if statements. In the example below, I’m setting an if statement to make sure the function foo() only runs when the number variable is bigger than 6.

Well, the same could be stated simply with a logical expression. If the first expression (number > 6) is false, the second will be short-circuited. If true, it runs.

A short-circuit can also be used to replace a variable when the intended value is not available. In the example below, the greet function takes in an argument name.

When name is passed into the function call, name is true enough that ‘you’ can be short-circuited. If not, it’s run and returned as the value to be stored in the variable name.

The same can be achieved with a simple default value on the function’s parameter, but for the sake of example I’m using the short-circuit as an alternative method.

Short-circuiting returns more than booleans

As seen in the example above, this mechanism doesn’t only return true or false values. It returns whatever-the-value-is of the last evaluated expression.

In the case below, ‘Frank’ is true enough that ‘you’ does not need to be evaluated. But if the first expression were false enough, i.e. undefined, then the returned value would be true.

In essence, that’s what was happening in the function detailed above.

No items found.