2

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?

FZs
  • 11,931
  • 11
  • 28
  • 41
francis
  • 235
  • 4
  • 15
  • 1
    One difference is the way it handles `false` – Matt Nov 26 '20 at 13:00
  • `a || b === a ? a : b` , `a ?? b === a != null ? a : b` – Felix Kling Nov 26 '20 at 13:55
  • 1
    One doesn't have to look further than the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator). – Felix Kling Nov 26 '20 at 13:56
  • 2
    *"For example, the below expressions return the same results."* You can find lots of examples where specific values produce the same results with different operators. E.g. `0 + 0`, `0 - 0`, `0 * 0` all produce `0`, yet I hope no one would argue that those operators do different things. If you want to understand the difference between operators, looking at a single example is not enough. – Felix Kling Nov 26 '20 at 13:58

1 Answers1

4

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.

Phillip
  • 4,341
  • 2
  • 15
  • 24