DEV Community

Cover image for Why short-circuit in programming?
Usenmfon
Usenmfon

Posted on

Why short-circuit in programming?

From how data binding and storage works, type of javaScript values: numbers, strings, booleans, null and undefined values. The concept of short-circuiting logical operations is imperative for wrting faster and efficient programs.

FYI:there's lot of differences between logical and comparison operators. But one similarity they share is that they both return a boolean result/value (i.e. True or False).
Logical operators majorly includes the &&(AND), ||(OR), and !(NOT).

Short-circuiting is where an expression is stopped being evaluated as soon as its outcome/result is determined.

That is to say, instead of checking the outcome of the two expressions, we can actually use the result of one expression to determine the output of the whole operation. When dealing with the && operator which evaluates as thus:

True && True = True
True && False = False
False && True = False

False && False = False

Since the presence of a false value in an expression renders the whole operation false, it would be pertinent to always place the "value/expression" that will result in a false result first in the expression, so as to save memory operation and increase speed of evaluation. The && operator is always looking for the first false statement to work on.

Checkout these examples:

console.log(null && "AnyString")
output: null

console.log("Okay" && "Confirm")
output: Confirm

console.log("user" && null)
output: null
Enter fullscreen mode Exit fullscreen mode

While working with the || operator, it is pertinent to place the "value" that would evaluate to true first in an expression. This is the modus operandi of || operator
True || True = True
True || False = True
False || True = True
False || False = False

console.log(null || "Agnes")
output: Agnes

console.log("user" || "non-user")
output: user

console.log("format" || null)
output: format
Enter fullscreen mode Exit fullscreen mode

Checking for the max number; notice that the LH expression maxNumber == null is intentionally made to be false.

function findMax(maxNumber) {
    if (maxNumber > 2 || maxNumber == null) {
        console.log(`The heighest number is: ${maxNumber}`);
    }
}

findMax(Math.max(4, 31, 6))
Enter fullscreen mode Exit fullscreen mode

Thus, as the RH operation evaluates to true, the LH operation is truncated.
The effect of this process can really be seen while working with functions.

Discussion (0)