There are two primitive types in javascript: null and undefined. These two types often make JavaScript developers confused, when is null, and when is undefined?
The undefined type has only one value, which is undefined. When the declared variable has not been initialized, the default value for the variable is undefined. The null type also has only one value, which is null. Null is used to represent an object that does not already exist, and is commonly used to indicate that a function is attempting to return a nonexistent object.
JS Code
- var ovalue;
- Alert (Ovalue = = undefined); //output "true"
This code shows true and the value representing Ovlaue is undefined because we did not initialize it.
JS Code
- Alert (null = = document.getElementById (' notexistelement '));
When a DOM node with ID "notexistelement" does not exist on the page, this code shows "true" because we are trying to get a nonexistent object.
JS Code
- 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, and the second line of code is confusing, why is the type of NULL another object? In fact, it was a mistake originally implemented by JavaScript, which was later ECMAScript. Today we can explain that NULL is a placeholder for an object that does not exist, but it is important to be aware of this feature when actually coding.
JS Code
- Alert (null = = undefined); //output "true"
ECMAScript that undefined are derived from null, so they are defined as equal. But what if, in some cases, we must differentiate between these two values? You can use the following two methods.
JS Code
- Alert (null = = = undefined); //output "false"
- Alert (typeof null = = typeof undefined); //output "false"
Using the TypeOf method, as mentioned earlier, NULL is not the same as the type of undefined, so the output is "false". and = = = Absolute equals, where null = = = undefined output false.
The difference between null and undefined in JS