空合并运算符 (??) 与 ECMAScript 中的逻辑 OR 运算符 (||) 有何不同?

fra*_*cis 6 javascript logical-or ecmascript-2020 nullish-coalescing

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 })
Run Code Online (Sandbox Code Playgroud)

result:

{
    orOperator:"B",
    nullishOperator:"B"
}
Run Code Online (Sandbox Code Playgroud)

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

Phi*_*lip 9

||-运算符的计算结果为右手边当且仅当左手边是一个falsy值。

-??运算符(空合并)当且仅当左侧为null或时才对右侧求值undefined

false, 0, NaN, ""(空字符串) 例如被认为是假的,但也许你真的想要这些值。在这种情况下,??-operator 是正确的操作符。