There are 2 special values in JavaScript that represent the absence of information: null and undefined. I personally think the difference between these two special values can be understood from the following perspective:
It represents a container that stores information (such as a variable that has previously been assigned a value), but the content in the container is empty.
It means that there is no container for storing information.
Null in JavaScript is no different from null in most other programming languages. It is basically used to indicate that the information value is empty; while in JavaScript, the expression returns the result undefined in the following situations:
1. A variable that has never been assigned a value.
2. Access the property value that does not exist in an object.
3. Access members that do not exist in the array.
4. Call a function without a return statement.
5. Call a function whose return statement is empty ("return ;").
In fact, like Infinity and NaN, undefined is a global variable in JavaScript and can even be assigned other values in ECMAScript 3. ECMAScript 5 corrected this error and set the undefined variable to read-only.
For comparisons between null and undefined, the === congruent operator can be used. If the normal == operator is used, null is equivalent to undefined:
(null == undefined);//true
(null === undefined);//false
During the programming process, if you need to assign a null value to a variable, null is generally used instead of undefined. The reason is:
It is generally believed that information is missing at the system level and at the error level.
It is generally believed that the information value at the programming level and the logical operation level is empty.
If type conversion is involved in the program, the results of null and undefined when converted to the number type are different:
The result of converting to number is NaN.
The result of converting to number is 0.
It is worth mentioning that the result of converting an empty string and an empty array into a number is also 0.
As for why two values that represent "no" are designed in JavaScript, you can refer to Ruan Yifeng's blog post.
experiment
In the following experimental code, the expression results are undefined:
var a;
(a);
function Sample(x){
= x;
}
var s = new Sample();
()
();
var n = [2,3,4];
(n[8]);
function test(){
//no return value for this function
}
(test());
function test2(){
return;
}
(test2());