Nullish coalescing operator (??)

 

Nullish coalescing operator (??)

 

Syntax 

leftExpression ?? rightExpression

 

The nullish coalescing (??) operator is a logical operator that returns its right-hand operand when its left-hand operand is empty or undefined, and returns its left-hand operand otherwise.

 

const foo = null ?? 'default string';
console.log(foo);

const baz = 0 ?? 42;
console.log(baz);

 

The nullish coalescing operator can be considered a special case of the logical OR operator (||). It returns the right operand if the left operand is a false value, not just null or undefined. In other words, if you use || If you want to provide some default value to another foo variable, you may encounter unexpected behavior if you consider some dummy values ​​to be usable (eg '' or 0)

 


Tags:

Share: