Middle
What is the difference between logical OR (||) and the null-coalescing operator (??)?
sobes.tech AI
Answer from AI
The logical OR operator (||) and the nullish coalescing operator (??) are similar but have important differences in behavior when checking values.
-
The || operator returns the first operand that is truthy in a logical context. If the first operand is "falsy" (false, 0, '', null, undefined, NaN), it returns the second.
-
The ?? operator returns the first operand if it is not null or undefined; otherwise, it returns the second.
Example:
const a = 0;
console.log(a || 42); // 42, because 0 is falsy
console.log(a ?? 42); // 0, because 0 is not null or undefined
Thus, ?? is useful when you want to assign a default value only if the variable is null or undefined, not for all "falsy" values.