JavaScript - Nullish coalescing operator
The JavaScript nullish coalescing operator ?? returns right-hand side operand when left-hand side operand is null or undefined, otherwise returns left-hand side operand.
This can be contrasted with the logical OR || operator, which returns the right-hand side operand if the left operand is any falsy value (a value that is considered false in a Boolean context), not only null or undefined.
Example:
The example below shows how to use nullish coalescing operator.
const nullValue = null; const someNumber = 50; var valA = nullValue ?? "default for A"; var valB = someNumber ?? 0; var txt; txt = valA + "<br>"; txt = txt + valB + "<br>";
The output (value of txt) after running above script will be:
default for A 50
No chaining with AND or OR operators
It is not possible to combine both the AND (&&) and OR operators (||) directly with ??. In such cases, a SyntaxError will be thrown:
null || undefined ?? "foo"; // raises a SyntaxError true || undefined ?? "foo"; // raises a SyntaxError
However, parenthesis can be used to explicitly indicate precedence.
(null || undefined) ?? "foo"; // returns "foo"
❮ JavaScript - Operators