两者都表示"无值",但具有不同的意图和来源。
undefined: 一个值的缺失,通常由 JavaScript 引擎设置——声明但未赋值的变量、缺失的 object 属性、未传递的 function 参数,或没有return的 function。null: 一个"空"值,赋予它来表示"这里故意什么都没有"。
let a; // undefined — declared, not assigned
const obj = {};
obj.missing; // undefined — property doesn't exist
function f() {}
f(); // undefined — no return
const b = null; // null — you chose to empty it
null == undefined; // true — loose equality treats them as equal
null === undefined; // false — different types
typeof undefined; // "undefined"
typeof null; // "object" (historical bug)
const value = input ?? "default"; // defaults on EITHER null or undefined
user?.address?.city; // optional chaining — undefined if any link is null/undefined
使用 null 故意清除一个值(例如"无选中用户"),并将 undefined 视为"尚未设置"。??(nullish coalescing)和 ?.(optional chaining)操作符同时处理两者,这就是为什么它们被广泛使用。