Similarities (although the headline is differences, but we also talk about similarities)
undefined
withnull
Is the basic data type of JavaScript.
The basic data types in JavaScript are those that store simple data segments, including: underdipay, NULL, Boolean, Number and String. A reference type is an object that may consist of multiple values, including: object, array, Map, Set, etc.
- The Boolean values of both are
false
The difference
concept
Undefined represents a nonexistence of value and null represents no value. Can be understood with a piece of code.
let a;
console.log(a);
// undefined
let b = null;
console.log(b);
//null
Copy the code
From the above code, undefined means that the variable has been declared but not assigned. Because its value does not exist, it is undefined. Null indicates that the variable is declared and assigned to null (null), so the result is NULL.
Comparison and distinction
To compare
null= =0
//false
null= =""
//false
null= =false
//false
undefined= =0
//false
undefined= =""
//false
undefined= =false
//false
undefined= =null / / attention! Attention! Attention!
//true
undefined= = =null / / attention! Attention! Attention!
//false
Copy the code
Differentiation (1)
- Check if the variable is null
age === null
- Check if the variable is undefined
age === undefined
- In two cases
if( ! age ){ ... do something... }
Differentiation (2)
- Check if the variable is null
let age = null;
typeof age;
//object
Copy the code
- Check if the variable is undefined
let age;
typeof age;
//undefined
Copy the code
Is null an object? Why is typeof age output null?
Null is not an Object, although typeof age outputs Object. This is a legacy. The original version of JS used a 32-bit system that stored the type information of a variable in a low place for performance purposes. Therefore, it is wrongly judged as Object.
conclusion
It just says how they behave. You can think of null and undefined as separate empty sets. Because empty sets do not have any elements of their own, they have no elements and are never equal, so they are always false. Js null and undefined are equivalent to having two subempty sets in a full set, which is incorrect. However, for clarity, you can only treat undefined as an alias for NULL. Empty sets are not equal to empty sets, so undefined is not equal to null.