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

╄→尐↘猪︶ㄣ 提交于 2021-01-27 18:48:10

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/65022531/how-is-the-nullish-coalescing-operator-different-from-the-logical-or-operat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!