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:
1.null represents a container that stores information (such as a variable that has been assigned a value before), but the content in the container is empty.
2. undefined means that there is no container used to store 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:
The code copy is as follows:
console.log(null == undefined);//true
console.log(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:
1. Undefined is generally considered to be a lack of information at the system level and error reporting level.
2.null is generally considered to be the programming level and the information value at 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:
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 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:
The code copy is as follows:
var a;
console.log(a);
function Sample(x){
this.x = x;
}
var s = new Sample();
console.log(sx)
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());