紀錄工作經驗、相關知識,解決技術相關問題。

Javascript

JS nullish coalescing(??):與 || 的差別與預設值寫法

JS nullish coalescing(??):與 || 的差別與預設值寫法 特色圖片

JS nullish coalescing(??,空值合併運算子)是邏輯運算子:左邊的運算元(operand,樂詞網譯為「運算元」)是 null 或 undefined 時,回傳右邊的運算元,否則回傳左邊的運算元。常用來替「可能沒有值」的變數提供預設值。

const name = null;

console.log(name ?? "訪客");   // 訪客

語法

x ?? y
  • x:左邊的運算式。
  • y:右邊的運算式,只有在 x 是 null 或 undefined 時才會被計算。
  • 回傳值:x 是 null 或 undefined 時回傳 y,否則回傳 x。

MDN 說明,?? 可以看成是 || 的特例:|| 在左邊是任何 falsy 值時回傳右邊,?? 則只在左邊是 null 或 undefined 時才回傳右邊。

只有 null 和 undefined 會用到預設值

下面三個變數,只有 null 會得到預設值,空字串與數字 42 都保留原值:

const nullValue = null;
const emptyText = "";
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);   // (空字串)
console.log(valC);   // 42

valB 的結果是空字串,因為空字串不是 null 也不是 undefined。

和 || 的差別

過去要設定預設值,常見寫法是用邏輯 OR(||)。但 || 會把左邊轉成布林來判斷,所以 0、""、NaN、false 這些 falsy 值也會被換成預設值。如果這些值在你的程式裡是有效的,結果就不是你要的:

const count = 0;
const text = "";

console.log(count || 42);     // 42
console.log(text || "hi!");   // hi!
console.log(count ?? 42);     // 0
console.log(text ?? "hi!");   // (空字串)

兩種運算子遇到各種左邊值的結果如下:

左邊的值用邏輯 OR 的結果用 ?? 的結果
null預設預設
undefined預設預設
0預設0
""預設空字串
false預設false
NaN預設NaN

要把 0、空字串當成有效的值時,用 ??;想連 falsy 值都換成預設,才用 ||。

短路求值

和 ||、&& 一樣,?? 只在需要時才計算右邊。左邊不是 null 或 undefined 時,右邊的運算式不會執行:

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());
// a was called
// c was called
// foo

console.log(b() ?? c());
// b was called
// false

a() 回傳 undefined,所以兩邊都執行;b() 回傳 false,不是 null 或 undefined,所以 c() 沒有被呼叫。

不能直接和 && 或 || 混用

MDN 說明,?? 不能直接和 && 或 || 寫在同一個運算式裡,否則會丟出 SyntaxError。要用括號明確標示順序:

function errorName(code) {
  try {
    new Function(code);
    return "no error";
  } catch (e) {
    return e.name;
  }
}

console.log(errorName('return null || undefined ?? "foo"'));     // SyntaxError
console.log(errorName('return true && undefined ?? "foo"'));     // SyntaxError
console.log((null || undefined) ?? "foo");                       // foo

搭配可選串連(?.)

?? 和可選串連(?.)都把 null、undefined 當成特殊值。?. 在物件可能是 nullish 時安全地讀取屬性,沒有值就得到 undefined;再接一個 ??,就能提供預設值:

const foo = { someFooProp: "hi" };

console.log(foo.someFooProp?.toUpperCase() ?? "not available");   // HI
console.log(foo.someBarProp?.toUpperCase() ?? "not available");   // not available

?. 的用法請參考它自己的語法文。

注意事項

  1. 只有 null 和 undefined 會換成預設值:0、""、false、NaN 都會保留。
  2. 不能直接和 &&、|| 混用:需要用括號標示順序,否則是 SyntaxError。
  3. 右邊是短路求值:左邊有值時,右邊的函式呼叫不會執行。
  4. ??=:另有空值合併指派運算子(??=),本文不介紹。

支援版本

依 MDN 瀏覽器相容性資料(browser-compat-data 8.1.10,查詢日期 2026-11-24):?? 從 Chrome 80、Edge 80、Firefox 72、Safari 13.1 開始支援,Node.js 從 14.0.0 開始,Deno 從 1.0 開始;Internet Explorer 不支援。

補充說明:範例在 Node.js 執行。MDN 的範例是預設值、|| 比較、短路求值與搭配 ?. 的四組,混用 &&/|| 的 SyntaxError 是依 MDN 說明另外示範的。null 的說明請參考它自己的語法文。

參考資料與延伸閱讀

發佈留言