Short-circuiting refers to the behavior of logical operators (&&, ||, and ??) where the second operand is only evaluated if the first operand does not definitively determine the result.
- Logical AND (
&&): If the first operand is falsy (a value which translates tofalsewhen evaluated in a boolean context, like0,null,undefined,NaN,""), the second operand is not evaluated, and the first operand is returned. If the first operand is truthy (a value which translates totruewhen evaluated in a boolean context), the second operand is evaluated and returned.
let result = false && console.log("Hello"); // "Hello" is not logged because false is a falsy value- Logical OR (
||): If the first operand is truthy, the second operand is not evaluated, and the first operand is returned. If the first operand is falsy, the second operand is evaluated and returned.
let result = true || console.log("Hello"); // "Hello" is not logged because true is a truthy value- Nullish Coalescing (
??): This operator is similar to the logical OR, but it only short-circuits if the first operand isnullorundefined(not just any falsy value). If the first operand isnullorundefined, the second operand is evaluated and returned. Otherwise, the first operand is returned.
let result = null ?? "default"; // result is "default"
let result = 0 ?? "default"; // result is 0