The nullish coalescing operator in JavaScript is defined as two question marks ??
. The left-hand side of the operator is returned as long as the right-hand side is neither null
nor undefined
and vice-versa.
Examples:
Right-hand side:
const example1 = 'Hello' ?? null //Result: Hello
const example2 = 'Hello' ?? undefined //Result: Hello
Left-hand side:
const example3 = null ?? 'Hello' //Result: Hello
const example4 = undefined ?? 'Hello' //Result: Hello
Exception:
The rule above holds true except when you are dealing with a falsy value.
Difference between nullish coalescing and OR (||)
Like nullish coalescing, OR (||) is a logical operator. The difference between them is that logical OR evaluates to true iff (if and only if) “one or more of its operands is true.” When used with Boolean values, a Boolean value is returned. However, when used with non-Boolean values, non-Boolean values are returned.[1]
Examples:
const a = 1;
const b = 2;
const c = 3;
const d = 4;
console.log(a > b || c > d); //(1 > 2 || 3 > 4) Result: false
Using const b = 2
from the previous example:
const string = "";
console.log(string || b); //Result: 2
[1] Logical OR (||)