المعرفة:: JavaScript الحالة::مؤرشفة المراجع:: syahshiimi’s notes, The Complete JavaScript Course 2022 From Zero to Expert


There are two operators that allows us to perform shortcircuiting in JavaScript.

  1. || operator
  2. && operator

How Does It Work?

  • The || operator will return the first truthy value of all the operands or the last, if they are all falsy
  • The && operator will instead return the first falsy value of all the operands or the last, if they are truthy
||&&
truthyfirstlast
falsylastfirst

What Does Shortcircuiting Mean?

When the operators are applied in an operand, it returns the first value to whichever the statement follows the conditons of the operator.

Limitations

The operands will always read 0 as the falsy value. We can circumvent it with the Nullish coalescing operator.

restaurant.numGuests = 0;
const guests1 = restaurant.numGuests || 10;
console.log(guests1); // 10

Examples

// Short Circuiting (&& and ||)
console.log("---- OR ----");
// Use ANY data type, return ANY data type, short-circuiting
console.log(3 || "Jonas"); // 3
console.log("" || "Jonas"); // Jonas
console.log(true || 0); // true
console.log(undefined || null);
console.log(undefined || 0 || "" || "Hello" || 23 || null); // Hello
const guests1 = restaurant.numGuests ? restaurant.numGuests : 10;
console.log(guests1); // 10
restaurant.numGuests = 23;
const guests2 = restaurant.numGuests || 10;
console.log(guests2); // 23
 
console.log("---- AND ----");
console.log(0 && "Jonas"); // Jonas
console.log(7 && "Jonas"); // Jonas
console.log("Hello" && 23 && null && "jonas"); // null
 
// check if method exists before using it
restaurant.orderPizza && restaurant.orderPizza("mushrooms", "spinach");