There are two kinds of primitive types in JavaScript: Null and Undefined. These two types often cause JavaScript developers to wonder when it is Null and when it is Undefined?
The Undefined type has only one value, that is, undefined. When the declared variable has not been initialized, the default value of the variable is undefined.
The Null type also has only one value, i.e. null. null is used to represent an object that has not existed yet, and is often used to represent a function that attempts to return an object that does not exist.
var oValue;
alert(oValue == undefined); //output "true"
This code is displayed as true, and the value representing oVlaue is undefined because we did not initialize it.
alert(null == ('notExistElement'));
When there is no DOM node with id "notExistElement" on the page, this code appears as "true" because we try to get an object that does not exist.
alert(typeof undefined); //output "undefined"
alert(typeof null); //output "object"
The first line of code is easy to understand, the type of undefined is Undefined; the second line of code makes people wonder, why is the type of null Object again? In fact, this is an error in the initial implementation of JavaScript, which was later used by ECMAScript. Today we can interpret it as null is a placeholder for an object that does not exist, but we still need to pay attention to this feature when actually encoding.
alert(null == undefined); //output "true"
ECMAScript believes that undefined is derived from null, so they are defined as equal. But, if in some cases we must distinguish between these two values, what should we do? The following two methods can be used.
alert(null === undefined); //output "false"
alert(typeof null == typeof undefined); //output "false"
As mentioned earlier, null and undefined types are different, so output "false". And === means absolutely equal, here null === undefined output false.