Middle
What is the difference between the nullish coalescing operator (??) and the logical OR (||)?
sobes.tech AI
Answer from AI
The nullish coalescing operator ?? returns the right-hand operand only if the left-hand operand is null or undefined. Unlike the logical OR ||, which returns the right-hand operand if the left-hand operand is falsy (i.e., false, 0, '', null, undefined, NaN).
Example:
const a = 0;
console.log(a || 42); // 42, because 0 is falsy
console.log(a ?? 42); // 0, because a is not null or undefined
Thus, ?? is useful when you want to set a default value only when the value is absent (null or undefined), and not for any falsy value.