The following is the text:
For "null" or "null reference", most programming languages have only one value. For example, null is used in Java. However, Javascript has two special values: undefined and null. They are basically the same, but their usage is slightly different. At the end of this series of tutorials, I will explain some changes in ECMAScript 6.
Undefined is assigned by the language itself. If a variable has not been initialized, its value is undefined:
> Var foo;
> Foo
Undefined
Similarly, when a parameter is missing, JavaScript will allocate an undefined:
> Function id (x) {return x}
> Id ()
Undefined
Null is used by developers to explicitly indicate that a value is missing. For example, for JSON. stringify ():
> Console. log (JSON. stringify ({first: 'jar'}, null, 4 ))
{
"First": "Jane"
}
Checking: Does a variable have a value?
If you want to know whether the variable v has a value, normally you need to check both undefined and null. Fortunately, both values are of the false type. Therefore, with only one judgment, you can check whether the two items are true at the same time:
If (v ){
// Value of v
} Else {
// No value for v
}
In part 1 of this series -- processing function parameters -- you will see more verification examples above. Note that this check also treats false,-0, + 0, NaN, and ''as" null ". If this is not what you want, you cannot use the above checking method.
You have two options.
Some people advocate not equal (! =) To verify v is neither undefined or null:
If (v! = Null ){
// Value of v
} Else {
// No value for v
}
However, you need to understand this! = Think that null is only equal to itself or undefined. I like to use more readable! =:
If (v! = Undefined & v! = Null ){
// Value of v
} Else {
// No value for v
}
In terms of performance, all the three school exams mentioned in this section are basically the same. So, which one to use depends on your needs and your taste. Some compression tools are even used! = Overwrites the last checklist.