null

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

null 值表示有意地缺失任何物件值。它是 JavaScript 的原始值之一,在布林操作中被視為假值

試一試

function getVowels(str) {
  const m = str.match(/[aeiou]/gi);
  if (m === null) {
    return 0;
  }
  return m.length;
}

console.log(getVowels("sky"));
// Expected output: 0

語法

js
null

描述

null 是用字面量 null 寫入的。null 不是全域性物件屬性的識別符號,不像undefined。相反,null 表示缺乏標識,表明一個變數沒有指向任何物件。在 API 中,當預期有物件但沒有相關物件時,常常會檢索到 null

js
// foo does not exist. It is not defined and has never been initialized:
foo; // ReferenceError: foo is not defined
js
// foo is known to exist now but it has no type or value:
const foo = null;
foo; // null

示例

nullundefined 的區別

在檢查 nullundefined 時,請注意相等 (==) 和全等 (===) 運算子之間的區別,因為前者會執行型別轉換。

js
typeof null; // "object" (not "null" for legacy reasons)
typeof undefined; // "undefined"
null === undefined; // false
null == undefined; // true
null === null; // true
null == null; // true
!null; // true
Number.isNaN(1 + null); // false
Number.isNaN(1 + undefined); // true

規範

規範
ECMAScript® 2026 語言規範
# sec-null-value

瀏覽器相容性

另見