Differences between Null and Undefined in JS --, jsnullundefined
There are 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.
Js Code
- VarOValue;
- Alert (oValue = undefined); // output "true"
This code is displayed as true, indicating that the value of oVlaue is undefined because it is not initialized.
Js Code
- 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.
Js Code
- Alert (TypeofUndefined); // 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.
Js Code
- 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.
Js Code
- Alert (Null=== Undefined); // output "false"
- Alert (Typeof Null=TypeofUndefined); // 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.