在JavaScript中,null和undefined是两个特殊的值,表示缺少值或未定义的状态。它们之间有以下区别:
null:表示一个空值或没有对象的值。它是一个关键字,可以被赋值给任何变量。undefined:表示一个未定义的值,即变量声明但未赋值时的默认值。在访问未初始化的变量或不存在的属性时,返回undefined。
区别总结如下:
null是人为赋予一个”空值”给变量,表示明确地设置为没有值。undefined表示变量未定义或者对象属性不存在。- 在判断值是否为空时,
null需要使用===进行严格相等比较,而undefined通常可以使用==进行松散相等比较。 - 当函数没有返回值时,默认返回
undefined。 - 对于函数参数,如果没有传递对应的参数,其值将是
undefined。
示例代码:
let nullValue = null;
let undefinedValue;
console.log(nullValue); // 输出: null
console.log(undefinedValue); // 输出: undefined
console.log(typeof nullValue); // 输出: object
console.log(typeof undefinedValue); // 输出: undefined
console.log(nullValue === undefinedValue); // 输出: false
console.log(nullValue == undefinedValue); // 输出: true
function exampleFunc(param) {
console.log(param); // 输出: undefined
}
exampleFunc(); // 没有传递参数
需要注意的是,尽量避免将undefined和null用于除了判断以外的其他目的。它们在不同上下文中可能会有不同的含义和行为。
搬瓦工中文网






