This article mainly introduces the differences between null and undefined in JavaScript. There are two special values in JavaScript that indicate that the information does not exist: null and undefined. This article mainly describes the differences between them, for more information, see the following special values in JavaScript: null and undefined. I personally think the difference between the two special values can be understood from the following perspectives:
1. null indicates a container with stored information (for example, a variable with previously assigned values), but the content in the container is empty.
2. undefined indicates that there is no container for storing information.
Null in JavaScript is similar to null in most programming languages. It is basically used to indicate that the information value is null. In JavaScript, the returned result is undefined in the following cases:
1. a variable that has never been assigned a value.
2. Access a property value that does not exist for an object.
3. Access a member that does not exist in the array.
4. Call a function without a return statement.
5. Call the function with the return statement being null ("return.
In fact, like Infinity and NaN, undefined is a global variable in JavaScript and can even be assigned to other values in ECMAScript 3. ECMAScript 5 corrected this error and set the undefined variable to read-only.
For comparison between null and undefined, you can use the equal = Full operator. If the = Operator is used, null and undefined are equivalent:
The Code is as follows:
Console. log (null = undefined); // true
Console. log (null ===undefined); // false
In programming, if you need to assign a null value to a variable, null instead of undefined is generally used. The reason is:
1. undefined is generally considered to be missing information at the system level and Error Reporting level.
2. null is generally considered to be a program-level information value at the logic operation level.
If type conversion is involved in a program, when the type is converted to number, the results of null and undefined are different:
1. The result of undefined conversion to number is NaN.
2. The result of converting null to number is 0.
It is worth mentioning that the result of converting an empty string and an empty array to a number is also 0.
For how to design two values in JavaScript that indicate "NONE", refer to Ruan Yifeng's blog post.
Lab
In the following experiment code, the expression result is undefined:
The Code is as follows:
Var;
Console. log ();
Function Sample (x ){
This. x = x;
}
Var s = new Sample ();
Console. log (s. x)
Console. log (s. notExistVariable );
Var n = [2, 3, 4];
Console. log (n [8]);
Function test (){
// No return value for this function
}
Console. log (test ());
Function test2 (){
Return;
}
Console. log (test2 ());