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

2

24

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?

Consociate answered 26/11, 2020 at 12:58 Comment(4)
One difference is the way it handles falseFoundling
a || b === a ? a : b , a ?? b === a != null ? a : bPinball
One doesn't have to look further than the MDN documentation.Pinball
"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.Pinball
A
45

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.

Anishaaniso answered 26/11, 2020 at 13:6 Comment(0)
F
-2

If you are intended to provide a default value to a number that may potentially be NaN, do this:

a = a || 0

// Not this
// a = a ?? 0

Also see convert NaN to zero.

Explanation:

Both operators are common for providing a default value for a variable. A situation for handling possible NaN value may mark some difference:

let userAge = null

let age1 = userAge || 21
let age2 = userAge ?? 21
console.log(age1) // 21
console.log(age2) // 21
let userAge = parseFloat(null)

let age1 = userAge || 21
let age2 = userAge ?? 21
console.log(age1) // 21
console.log(age2) // NaN

If you wish to let a value with possible NaN value fall back to a default value, choose ||. Double question mark aka the nullish operator ?? doesn't do the fallback here.

Fitful answered 7/7, 2023 at 5:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.