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 null data type is object, then the five data types of JS are string,boolean,number,null,undefine, so what is null for? Because the constant value of NULL is the object type?
Null is an object type Ah, undefine is the undefine type.
Null==undefine, I can still understand.
If NULL is the object type, what is the use of a null object of the five big data types?
So JS clearly should be the four data types.
And JS has programming ideas a book? I'd love to read it.
Null and undifined differences in JS and the role of NULL