Nullish Coalescing Operator (??)

Nullish Coalescing Operator (??)

Nullish coalescing operator is a logical operator. It returns right hand operand only if left hand operand is null or undefined.

Syntax

leftOperand ?? rightOperand

Examples:

const user = null ?? "user";
console.log(user);
/* output:  user  */

const num = 1 ?? 4;
console.log(num);
/* output: 1  */

Difference between Logical OR ( || ) and Nullish coalescing operators:

Nullish coalescing operator seems like logical OR(||) operators but unlike logical OR(||) operator which return right hand operand if left hand operand is any falsy value, nullish coalescing operator return right hand operand if only left hand operand is null or undefined.

Examples:

const name = "" ?? "Raj";
console.log(name);
/* output: "" , here "" is treated as truthy value. */

const value = undefined ?? "Value";
console.log(value);
/* output: Value, here undefined is treated as falsy value. */

const num = 0 ?? 6;
console.log(num);
/* output: 0 , here 0 is treated as truthy value. */

To read more