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.
Distinguish between null and undefined in JavaScript