Null and undefined are two types of JavaScript, and the values of the types are as follows:
type |
value |
Null |
Only one value is null |
Undefined |
Only one value undefined |
Null indicates that the variable takes a value of null– in other words, the value is not a string nor a number or a true value or an object.
Undefined indicates that the variable has been declared, but is not assigned, or is assigned a value of undefined.
Like what:
var A; Variable declared, not assigned
var b = undefined; Variable is declared, the assignment undefined
A = = = B;
The output of a = = = B is true.
So we can simply distinguish between them:
Undefined indicates that the value of the variable was not found-no value was found
Null indicates that the value of the variable is found null– find the value
Look at the judgment null and undefined
The judgment here refers to whether the value of the variable is null or undefined
Null and undefined are the only values of the type they belong to. So it's very convenient to judge the method as long as we use the identity comparison (= = =).
A that undefined
var A;
A = = = undefined;
The code above will output true, that is, a is undefined.
A is null
var a = null;
A = = = NULL;
The code above will output true, that is, A is null.
Of course, the identity comparison has the premise that the variable already exists, and that referencing an undeclared variable throws an error if the variable has not been declared.
i = = = undefined;
The above code throws an error after execution:
REFERENCEERROR:I is not defined
So it's safer to use TypeOf to check whether a variable is undefined:
typeof i = = ' undefined '; If I was not declared, or I was declared but not assigned, the result is true
But typeof check that the value of the variable is NULL, the output is "object", this conclusion is not accurate. The following methods are true and secure:
var a = null;
Object.prototype.toString.call (a). Slice (8,-1);
It outputs null, indicating that the value of variable A is null.