This article mainly introduces the difference between Null and Undefined in JavaScript. This article provides multiple code instances to explain the differences between them, you can refer to the following two primitive types in JavaScript: Null and Undefined. These two types often make JavaScript developers confused, when is it Null, and when is it 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, that is, null. Null indicates an existing object. it is often used to indicate that a function attempts to return a non-existing object.
The code is as follows:
Var oValue;
Alert (oValue = undefined); // output "true"
This code is displayed as true, indicating that the value of oVlaue is undefined because it is not initialized.
The code is as follows:
Alert (null = document. getElementById ('notexistelement '));
When a DOM node with the id "notExistElement" does not exist on the page, this code is displayed as "true" because we try to obtain a nonexistent object.
The code is as follows:
Alert (typeof undefined); // output "undefined"
Alert (typeof null); // output "object"
The first line of code is easy to understand. the undefined type is Undefined. The second line of code is confusing. why is the null type an Object? In fact, this was an error originally implemented by JavaScript and was subsequently followed by ECMAScript. Today, we can interpret null as a placeholder for a non-existent object, but pay attention to this feature in actual encoding.
The code is as follows:
Alert (null = undefined); // output "true"
ECMAScript considers undefined to be derived from null, so they are defined as equal. However, in some cases, we must differentiate these two values. what should we do? You can use the following two methods.
The code is as follows:
Alert (null = undefined); // output "false"
Alert (typeof null = typeof undefined); // output "false"
The typeof method has already been used. the type of null is different from that of undefined, so the output is "false ". ===Indicates that the value is absolutely equal. here, null ===undefined outputs false.