In JavaScript, the definition of null value varies from project to project. Usually, when connecting with background interface, empty string “”, null and undefined are needed to determine whether data exists. This article takes you through null and undefined again.
Usually null and undefined are the judgment conditions for no value. But if the equality operator == is used to compare them, true is returned. But null is usually used to explicitly not assign to variables, while undefined is used implicitly by the JavaScript engine itself to not assign to variables. The two basic data types are used to fulfill similar requirements, but are not strictly the same in type. Use typeof to get its type, null returns object, and undefined returns undefined. It is clear that === returns false.
console.log(undefined == null); // true
console.log(undefined === null); // false
console.log(typeof null); // object
console.log(typeof undefined); // undefined
Copy the code
A null value judgment
As mentioned above, determining null values can be interpreted differently in different projects, and the following code snippet can determine all types of null values.
const isEmpty = (x) => { if (Array.isArray(x) || typeof x === "string" || x instanceof String) { return x.length === 0; } if (x instanceof Map || x instanceof Set) { return x.size === 0; } if ({}.toString.call(x) === "[object Object]") { return Object.keys(x).length === 0; } if (! isNaN(parseFloat(x)) && isFinite(x)) { return false; } return ! x; }; console.log(isEmpty(null)); // true console.log(isEmpty(undefined)); // true console.log(isEmpty([])); // true console.log(isEmpty({})); // true console.log(isEmpty("")); // true console.log(isEmpty(new Set())); // true console.log(isEmpty(0));Copy the code
Why is NULL object?
Null is an object. It is incorrect to say that null is an object. In fact, NULL is a basic type in JavaScript.
This is actually a bug in the language that unfortunately cannot be easily fixed because it breaks the existing code base. However, there is actually a logical explanation for why NULL is an object in JavaScript.
In the original version of JavaScript, values were stored in 32-bit units. The first three bits represent the data type label, and the last three bits represent the value.
For all objects, the type marker bit is 000, and NULL is considered a special value in JavaScrip from the earliest version. Null represents a null pointer. However, there are no Pointers in JavaScript like in C, so null simply means nothing or invalid, represented by all zeros. So it has 32 bits that are 0’s. Thus, whenever the JavaScrip interpreter reads NULL, it thinks the first three bits are of type Object.