[Solved] Similarities and differences between null and undefined data types in javascript

Similarities:

  • The null type and the undefinedf type have only one literal value.
  • Both null type and undefined type will be converted to false when converted to boolean type, so pass the non operator! When the result is true, it cannot distinguish between the null type and the undefined type.
  • When both are converted into objects, a reference exception will be thrown.

Differences:

  • null is a keyword in JavaScript and undefined is a global variable in JavaScript.
  • When using the typeof operator to detect, the value of the undefined type will return undefined, and the null type will return object.
  1. Undefined type

There is only one value, that is, the special undefined, which means that the data has not been defined or a non-existing value of the acquired object. The following are the common cases of undefined:

  • When a variable is declared with var, but not initialized, it returns undefined.
var box;
alert(box); //The return value is undefined
  • A function that does not have an explicit return value, but uses the return value elsewhere, will return undefined.
function abc(){};
alert(function());
var obj = {
    name = 'chen'
}
alert(obj.like);
  • When getting a non-existent property of an object, undefined is returned.
var obj = {
    name = 'chen'
}
alert(obj.like);
  • The function definition uses multiple formal parameters, and the number of parameters passed when calling is less than the number of formal parameters, then the unmatched parameter is undefined.
function abc(pa1,pa2,pa3){
    document.write("pa1");
}
abc(1,2)

2. Null type

It is a specified data type, representing a null object reference, and the typeof operator will return an object if it detects null. The following are three common null cases:

  • Numbers and strings are allocated a certain amount of memory space when they are defined. If the value of a variable is equal to null, it means that the system has not allocated space for the variable.
var box = null;
alert(typeof box);
  • When JavaScript gets the DOM element, it does not get the specified element object and returns null.
document.getElementBuId("id");
  • When capturing with regular expressions, if there is no capture result, it will return null
test.match(/a/);