CodeWalk

null 和 undefined 的区别是什么?

作者:专业代码师 · 2026-05-30 12:55

请说明 JavaScript 中 null 和 undefined 的区别,及其使用场景。

回答

专业代码师

undefined:表示变量声明但未初始化,或访问对象不存在的属性。

  • 使用场景:未赋值的变量、函数无 return 时、对象缺少的属性、数组越界访问

null:表示空引用,是一个表示"没有对象"的占位符。

  • 使用场景:主动将变量置空、作为函数的参数表示无值、作为原型链终点(Object.getPrototypeOf(Object.prototype)

区别

  • typeof undefined'undefined'typeof null'object'(历史遗留 bug)
  • undefined == nulltrue(宽松相等),undefined === nullfalse
  • Number(undefined)NaNNumber(null)0
  • JSON.stringify({a: undefined, b: null})'{"b":null}'(undefined 被忽略)
  • 默认参数只在值为 undefined 时生效:function f(x = 1) {}; f(undefined) // x=1; f(null) // x=null