Skip to content

Short Circuiting in JavaScript

Posted on:November 7, 2023 at 07:44 AM

In JavaScript, you can use the && and || operators for short-circuiting, which can help you write more concise and efficient code. Let’s explore how these operators work.

Short Circuiting with && (Logical AND)

The && operator returns false as soon as it encounters any falsy value among its operands and returns the last truthy value if all the operands are truthy. For example:

console.log("Hello" && 23 && null && "Joe"); // Output: null

In the above example, the && operator stops evaluating as soon as it encounters null (a falsy value) and returns it.

Short Circuiting with || (Logical OR)

The || operator returns the first truthy value among its operands or the last value if all of them are falsy. For example:

console.log(3 || "Joe"); // Output: 3
console.log("" || "Joe"); // Output: Joe
console.log(true || 0); // Output: true
console.log(undefined || null); // Output: null
console.log(undefined || 0 || "" || "Hello" || 23 || null); // Output: Hello

In these examples, the || operator returns the first truthy value it encounters or the last value if all are falsy.

Short Circuiting for Default Values

Short-circuiting is commonly used for setting default values. Instead of writing a ternary conditional (e.g., condition ? valueIfTrue : valueIfFalse), you can use the || operator:

const guests1 = restaurant.numGuests ? restaurant.numGuests : 10;
const guests2 = restaurant.numGuests || 10;

The guests2 assignment uses the || operator to set guests2 to restaurant.numGuests if it’s a truthy value, and if it’s falsy (including the case where restaurant.numGuests is 0), it defaults to 10.

However, if you want to avoid the issue when restaurant.numGuests is 0, you can use the Nullish Coalescing Operator (??):

const guestCorrect = restaurant.numGuests ?? 10;
console.log(guestCorrect);

The ?? operator only returns the right-hand operand if the left-hand operand is null or undefined, but not for other falsy values like 0 or an empty string. This makes it a safer choice for setting default values when working with potentially falsy values.