Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the nullish coalescing operator (??) different from the logical OR operator (||) in ECMAScript?

ES2020 introduced the nullish coalescing operator (??) which returns the right operand if the left operand is null or undefined. This functionality is similar to the logical OR operator (||). For example, the below expressions return the same results.

const a = undefined
const b = "B"

const orOperator = a || b
const nullishOperator = a ?? b
  
console.log({ orOperator, nullishOperator })

result:

{
    orOperator:"B",
    nullishOperator:"B"
}

So how is the nullish operator different and what is its use case?

like image 563
francis Avatar asked Nov 26 '20 12:11

francis


People also ask

What is a Nullish coalescing operator?

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

What are Nullish values in JS?

In JavaScript, a nullish value is the value which is either null or undefined . Nullish values are always falsy.

Does JavaScript have coalescing operator?

Note from January 2020: Nullish coalescing operator is available natively in Firefox 72 but optional chaining operator is still not.

When was Nullish coalescing operator added?

JavaScript made sure this can be handled with its nullish operator also known as the Null Coalescing Operator, which was added to the language with ECMAScript 2020. With it, you can either return a value or assign it to some other value, depending on a boolean expression.


1 Answers

The || operator evaluates to the right-hand side if and only if the left-hand side is a falsy value.

The ?? operator (null coalescing) evaluates to the right-hand side if and only if the left-hand side is either null or undefined.

false, 0, NaN, "" (empty string) are for example considered falsy, but maybe you actually want those values. In that case, the ?? operator is the right operator to use.

like image 87
Phillip Avatar answered Oct 05 '22 22:10

Phillip