首先我们知道undefined与null都属于 javascript 的 7 种基本类型。
(推荐教程:js教程)
let primitivetypes = ['string','number','null','undefined','boolean','symbol', 'bigint'];
它们是属于虚值,可以使用boolean(value)或!!value将其转换为布尔值时,值为false。
console.log(!!null); // falseconsole.log(!!undefined); // falseconsole.log(boolean(null)); // falseconsole.log(boolean(undefined)); // false
区别:
undefined是未指定特定值的变量的默认值,或者没有显式返回值的函数,如:console.log(1),还包括对象中不存在的属性,这些 js 引擎都会为其分配 undefined 值。
null是“不代表任何值的值”。 null是已明确定义给变量的值。 在此示例中,当fs.readfile方法未引发错误时,我们将获得null值。
在比较null和undefined时,我们使用==时得到true,使用===时得到false。
console.log(null == undefined); // true console.log(null === undefined); // false
以上就是undefined与null有什么区别的详细内容。