The JavaScript language is not strictly designed, and sometimes it is easy to confuse people. For example, the effectiveness of this variable is determined.
Here are several examples:
To understand why the above results are obtained, you must first understand the different meanings of undefined and null in JavaScript.
Here is a conclusion from instructor Ruan Yifeng's blog:
Null and undefined are basically synonymous, with only slight differences.
Null indicates "no object", that is, there should be no value.Typical usage:
(1) as a function parameter, it indicates that the function parameter is not an object.
(2) serves as the end point of the object prototype chain.
Undefined indicates "missing value", that is, there should be a value, but it is not defined yet.Typical usage:
(1) the variable is declared, but when no value is assigned, it is equal to undefined.
(2) when calling a function, the required parameter is not provided. This parameter is equal to undefined.
(3) the object does not have an attribute assigned a value. The value of this attribute is undefined.
(4) when the function does not return a value, undefined is returned by default.
In Java, the if condition must use a boolean expression. Therefore, when JavaScript is used, it is also customary to think so. In fact, when null, undefined, 0, "", and false in JavaScript are used as conditions for if, they are considered false.
Therefore, when determining a variable, you can use the following methods:
1. Accurately determine whether a variable is undefined
2. Accurately determine whether a variable is null
3. Determine whether a variable is null or undefined.
4. Determine whether the value is valid. You can directly use the variable name in the if expression. I often use it to determine whether the value of an input box is valid (note: if the variable value is 0, it will be treated as invalid)