JS: Nullish Coalescing Operator. (x ?? y)

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2020)

x ?? y

If x is defined, return x, else return y.

defined means it is not null nor undefined

usually used for assignement, e.g. const color = obj.color ?? "red";

console.assert((undefined ?? 4) === 4);
console.assert((null ?? 4) === 4);

console.assert((true ?? 4) === true);
console.assert((false ?? 4) === false);

console.assert((0 ?? 4) === 0);
console.assert((1 ?? 4) === 1);

console.assert(("" ?? 4) === "");
console.assert(("x" ?? 4) === "x");