Null and undefined are two basic data types in JavaScript, both of which can be used to represent the concept of “nothing”, but the semantic expression is actually used differently

describe

Most computer languages have only one value for the concept of “nothing”, such as NULL for C and C++, NULL for Java and PHP, None for Python, nil for Lua and Ruby, However, there are two basic data types in JavaScript, null and undefined, to represent the concept of “nothing”. Null and undefined are almost identical in many cases, such as if statements, which are automatically converted to false

let _null = null;
let _undefined = undefined;

if(! _null && ! _undefined)console.log("true && true");		// true & true
Copy the code

Null is considered equal to undefined in the == operator, as opposed to undefined in the === operator

console.log(null= =undefined);				// true
console.log(null= = =undefined);			// fasle
Copy the code

The use of null and undefined for “none” is a legacy. JavaScript was originally designed to only set null for “none”. According to C tradition, null was designed to automatically convert to zero. However, Brendan Eich, the designer of JavaScript, felt that this was not enough. In the first place, JavaScript was originally designed with null as an Object, which is why typeof(NULL) === Object, Although there was a proposal to change the type typeof null (NULL) === NULL, it was rejected because it would cause a lot of problems with older JavaScript scripts. Brendan Eich felt that the value of “none” had better not be an object, and if NULL was automatically converted to 0, It’s not easy to find errors, so Brendan Eich designed an undefine data type. Although null has a very high similarity with undefined, it needs to be distinguished in semantics and practical use. Undefined means there is no definition of the value. Null means that a value is defined and is null, so it is reasonable to set a value to NULL, such as obj.v = null, but it is not reasonable to set a value to undefined because it has been actively declared defined, and it is not reasonable to set undefined

The difference between

  • nullIt’s an object that means nothing,Number(null) === 0", undefinedIs a primitive value for "none",Number(undefined) === NaN“`
  • nullIndicates that a value is defined, but the value is null
    • As an argument to a function, indicating that the argument to the function is not an object
    • As the end of the object prototype chainOBject.getPrototypeOf(Object.prototype)
  • undefinedIndicates that no definition of the value exists
    • The variable is declared and not assignedundefined
    • The parameter that should have been provided when the function was called was not provided, and the parameter value isundefined
    • The object has no assigned attribute whose value is represented byundefined
    • The function returns no value, by defaultundefined