試一試
const foo = null ?? "default string";
console.log(foo);
// Expected output: "default string"
const baz = 0 ?? 42;
console.log(baz);
// Expected output: 0
語法
js
leftExpr ?? rightExpr
描述
空值合併運算子可以看作是邏輯或 (||) 運算子的一種特殊情況。後者在左側運算元為任何 假值時返回右側運算元,而不僅僅是 null 或 undefined。換句話說,如果您使用 || 為另一個變數 foo 提供一些預設值,如果您認為某些假值是可用的(例如,'' 或 0),您可能會遇到意外行為。有關更多示例,請參閱下文。
空值合併運算子的運算子優先順序是第五低,直接低於 ||,直接高於條件(三元)運算子。
不能將 AND (&&) 或 OR (||) 運算子直接與 ?? 組合使用。在這種情況下會丟擲語法錯誤。
js
null || undefined ?? "foo"; // raises a SyntaxError
true && undefined ?? "foo"; // raises a SyntaxError
相反,請提供括號以明確指示優先順序
js
(null || undefined) ?? "foo"; // returns "foo"
示例
使用空值合併運算子
在此示例中,我們將提供預設值,但保留除了 null 或 undefined 之外的值。
js
const nullValue = null;
const emptyText = ""; // falsy
const someNumber = 42;
const valA = nullValue ?? "default for A";
const valB = emptyText ?? "default for B";
const valC = someNumber ?? 0;
console.log(valA); // "default for A"
console.log(valB); // "" (as the empty string is not null or undefined)
console.log(valC); // 42
為變數賦值預設值
早些時候,當需要為變數賦值預設值時,一種常見的模式是使用邏輯或運算子 (||)
js
let foo;
// foo is never assigned any value so it is still undefined
const someDummyText = foo || "Hello!";
然而,由於 || 是一個布林邏輯運算子,左側運算元在評估時會被強制轉換為布林值,並且任何假值(包括 0、''、NaN、false 等)都不會被返回。如果您將 0、'' 或 NaN 視為有效值,此行為可能會導致意外後果。
js
const count = 0;
const text = "";
const qty = count || 42;
const message = text || "hi!";
console.log(qty); // 42 and not 0
console.log(message); // "hi!" and not ""
空值合併運算子透過僅在第一個運算元評估為 null 或 undefined(但不包括其他假值)時返回第二個運算元來避免此陷阱
js
const myText = ""; // An empty string (which is also a falsy value)
const notFalsyText = myText || "Hello world";
console.log(notFalsyText); // Hello world
const preservingFalsy = myText ?? "Hi neighborhood";
console.log(preservingFalsy); // '' (as myText is neither undefined nor null)
短路求值
與“OR”和“AND”邏輯運算子一樣,如果左側表示式既不為 null 也不為 undefined,則右側表示式不會被評估。
js
function a() {
console.log("a was called");
return undefined;
}
function b() {
console.log("b was called");
return false;
}
function c() {
console.log("c was called");
return "foo";
}
console.log(a() ?? c());
// Logs "a was called" then "c was called" and then "foo"
// as a() returned undefined so both expressions are evaluated
console.log(b() ?? c());
// Logs "b was called" then "false"
// as b() returned false (and not null or undefined), the right
// hand side expression was not evaluated
與可選鏈運算子 (?. ) 的關係
空值合併運算子將 undefined 和 null 視為特定值。 可選鏈運算子 (?.) 也如此,它對於訪問可能為 null 或 undefined 的物件的屬性很有用。將它們結合起來,您可以安全地訪問可能為空值的物件的屬性,並在其為空值時提供預設值。
js
const foo = { someFooProp: "hi" };
console.log(foo.someFooProp?.toUpperCase() ?? "not available"); // "HI"
console.log(foo.someBarProp?.toUpperCase() ?? "not available"); // "not available"
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # prod-CoalesceExpression |
瀏覽器相容性
載入中…