Perhaps the most interesting aspect of logical operators in JavaScript is their ability to execute code conditionally. JavaScript evaluates logical operators from left to right. If the first argument is sufficient to determine the outcome of the operator, JavaScript skips evaluating the second argument. This behavior is called short-circuiting and provides developers with the opportunity to write a more concise and readable code.

Up until recently, JavaScript had only two short-circuiting operators: && and ||. The nullish coalescing (??) operator is an ES2020 feature that brings a new short-circuiting operator to JavaScript, and it works differently from its counterparts.

In this article, we’ll first look at how short-circuiting in JavaScript works. Then we’ll see why the existing short-circuiting operators aren’t effective for specific use cases, and how the new nullish coalescing operator helps developers write less error-prone and more concise code.


Why is short-circuiting useful?

When we use logical operators (also known as short-circuiting operators) with boolean values, they return a boolean value. The logical AND (&&) operator, for example, returns true if both of its operands evaluate to true:

const a = 10;

console.log(a > 5 && a < 20);    // => true

If the left-hand operand of the && operator evaluates to false, the JavaScript interpreter is smart enough to know that the result of the operator will be false, so it doesn’t see any point in wasting resources to evaluate the right operand. This triggers what is known as short-circuiting.

#esnext #nodejs #web-development #es2020 #javascript

How short-circuiting in JavaScript works
1.05 GEEK