JavaScript null和 undefined 的区别是什么?

面试被问到,不是很会,学习下。

区别

null 表示没有对象(空对象指针),转化为数值时为 0 ,这也是为什么 typeof null 返回 object 的原因。

console.log(Number(null)) // 0
console.log(typeof null) // object

undefined 表示缺少值,转化为数值时为 NaN

console.log(Number(undefined)) // NaN

undefined 典型用法

  1. 变量被声明了,但没有赋值时,就等于 undefined 。
let num
console.log(num) // undefined
  1. 调用函数时,应该提供的参数没有提供,该参数等于 undefined。
function fun(a) {
  console.log(a) // undefined
}
fun()
  1. 对象没有赋值的属性,该属性的值为 undefined。
const obj = {}
console.log(obj.a) // undefined
  1. 函数没有返回值时,默认返回 undefined 。
function fun() {}
console.log(fun()) // undefined

null 的典型用法 :

  1. 作为函数的参数,表示该函数的参数不是对象,用于判断。
function fun(a) {
  if (a !== null) {
    // 进行一系列操作
  }
}
  1. 作为对象原型链的终点。
console.log(Object.prototype.__proto__) // null