Original article: javascript quirk 2: Two "non-values"-undefined and null
2: two null values: undefined and null
Translator: singleseeker
For "null" or "null reference", mostProgramming LanguageThere is 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. In thisSeries tutorialsFinally, 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;> fooundefined
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,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 areType false. Therefore, with only one judgment, you can check whether the two items are true at the same time:
If (v) {// v has a value} else {// v has no value}
InSeriesPart 1 -- processing function parameters -- you will see more examples of the above verification. 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) {// v has a value} else {// v has no value}
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) {// v has a value} else {// v has no value}
PerformanceAll the three school exams mentioned in this chapter 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.