The difference between null and undefined in JavaScript
Reference
JavaScriptTypical usage of null
As a function parameter, it means that the function parameter is not an object
function myFn(obj) {
if(null == obj) {
// code
}
}
As the end of the object prototype chain
Object.getPrototypeOf(Object.prototype);
When releasing the variable, assign null to the variable
let o={
code:'abc'
};
o = null;
Typical usage of undefined
The variable is declared but not assigned, the value of the variable is undefined
let o;
console.log(o); //undefined
The parameter that the function should provide is not provided when calling, then the value of the parameter that is not provided is undefined
function myFn(o) {
console.log(o);
}
myFn(); //undefined
Properties that the object does not contain, the value is undefined
let o={
code:'abc'
};
console.log(o.name); //undefined
When the function does not return a value, it returns undefined by default
function myFn(obj) {
obj = 'a';
}
console.log(myFn()); //undefined
Similarities between null and undefined
False when converted to boolean
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
The difference between null and undefined
The result is different when converted to a number. The result of null conversion is a valid number value of 0, and the result of undefined conversion is NaN.
console.log(Number(null)); // 0
console.log(Number(undefined)); // NaN
The two types are different, the type of null is object, and the type of undefined is undefined.
console.log(typeof null); //object
console.log(typeof undefined); //undefined
compare null and undefined
To distinguish between null and undefined, only congruence can be used. In congruence, it will strictly compare whether the two types are equal.
console.log(Boolean(null == undefined)); // true
console.log(Boolean(null === undefined)); // false
to sum up
After the above comparison, we have a clear understanding of these two types. Usually when we judge whether a variable has a valid value when writing code, we don't need to distinguish between the two, just use it as a Boolean type. But when we need to judge whether the property exists, we must strictly use the type to judge undefined. Finally, if we pass a numeric value, we must make a judgment first, and cannot be directly cast to a numeric type, otherwise null will cause us to get abnormal results, and undefined will directly calculate the invalid result NaN.