Null-value merge operator (??) Is a logical operator that returns the right-hand operand if the left-hand operand is null or undefined, otherwise returns the left-hand operand.
const foo = null ?? 'default value';
// foo -> 'default value'
const bar = undefined ?? 'default value';
// bar -> 'default value'
const foo1 = false ?? 'false value';
// foo1 -> false
const bar1 = 0 ?? 'zero value';
// bar1 -> 0
Copy the code
The Boolean or operator (| |) on the left operand is false value returns the right operand.
However, due to the | | is a Boolean logical operators, the left operand are forced into Boolean value for evaluation. Any false values (0, “, NaN, null, undefined) will not be returned. This leads to unexpected consequences if you use 0, “, or NaN as valid values.
let count = 0;
let text = "";
let qty = count || 42;
let message = text || "hi!";
console.log(qty); // 42 instead of 0
console.log(message); // "hi!" Instead of ""
Copy the code
The null-value merge operator avoids this trap by returning the second operand only if the first operand is null or undefined (and not some other false value) :
let myText = ' '; // An empty string (which is also a falsy value)
let notFalsyText = myText || 'Hello world';
console.log(notFalsyText); // Hello world
let preservingFalsy = myText ?? 'Hi neighborhood';
console.log(preservingFalsy); // '' (as myText is neither undefined nor null)
Copy the code
A short circuit
Like the OR AND logical operators, the right-hand expression is not evaluated when the left-hand expression is not null OR undefined.
That is, the right-hand side is evaluated only when the left-hand side expression is null or undefined
function A() { console.log("Function A is called."); return undefined; }
function B() { console.log("Function B is called."); return false; }
function C() { console.log('Function C is called'); return "foo"; }
console.log( A() ?? C() );
// Print "function A called", "function C called", "foo" in sequence
// A() returns undefined, so expressions on both sides of the operator are executed
console.log( B() ?? C() );
// Print "function B called", "false"
// B() returns false (neither null nor undefined)
// So the expression on the right is not executed
Copy the code
Reference: null merge operator – JavaScript | MDN