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?
false
– Foundlinga || b === a ? a : b
,a ?? b === a != null ? a : b
– Pinball0 + 0
,0 - 0
,0 * 0
all produce0
, 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