Member-only story
JavaScript: || and ?? Are Not the Same
In JavaScript, the logical operators ||
(logical OR) and ??
(nullish coalescing operator) may seem similar at first glance, but they have important differences in their behavior and usage.
The ||
operator returns the first truthy operand, or the last operand if all operands are falsy. This means that if any of the operands in an ||
expression evaluates to a truthy value, the entire expression will return that value. For example:
const x = 5 || 0;
console.log(x); // Output: 5
const y = false || "hello";
console.log(y); // Output: "hello"
In the first example, the expression 5 || 0
returns 5
because 5
is a truthy value. In the second example, the expression false || "hello"
returns "hello"
because "hello"
is the first truthy value encountered in the expression.
The ??
operator, on the other hand, returns the first operand that is not null
or undefined
, or the last operand if all operands are null
or undefined
. This means that if any of the operands in a ??
expression evaluates to a non-nullish value, the entire expression will return that value. For example:
const x = null ?? 5;
console.log(x); // Output: 5
const y = undefined ?? "hello";
console.log(y); // Output: "hello"
In the first example, the expression null ?? 5
returns 5
because 5
is the first…