Sobes.tech
Middle

What is the nullish coalescing operator (??) and how does it differ from the regular || operator?

sobes.tech AI

Answer from AI

The nullish coalescing operator (??) in JavaScript returns the right-hand operand if the left-hand operand is null or undefined; otherwise, it returns the left-hand operand.

The difference from the || operator is that || returns the right-hand operand if the left-hand operand is any "falsy" value (false, 0, '', null, undefined, etc.), whereas ?? considers only null and undefined.

Example:

const a = 0;
console.log(a || 42); // 42 — because 0 is considered falsy
console.log(a ?? 42); // 0 — because 0 is not null or undefined

This is important when you need to distinguish "absence of value" (null/undefined) from other falsy values.

What is the nullish coalescing operator (??) and how… - sobes.tech