当左侧操作数为 nullundefined 时,返回右侧操作数,否则返回左侧操作数。

$$edit$$
$$jsdemo$$
alert(null ?? 123) // 123
alert(undefined ?? 123) // 123
alert("abc" ?? 123) // abc

练习

  1. 说说以下代码的执行结果,为什么?
$$jsdemo$$
$$edit$$
alert("" || 123)
alert("" ?? 123)

alert(0 || 123)
alert(0 ?? 123)

alert(null ?? 123 ?? null ?? 456)

$$answer

$$jsdemo$$
$$edit$$
alert("" || 123) // 123
alert("" ?? 123) // 空字符串

alert(0 || 123) // 123
alert(0 ?? 123) // 0

alert(null ?? 123 ?? null ?? 456) // 123

$$