A few minutes before I got off work, I thoroughly understood the difference between undefined and null

content

foreword

1. Basic Concepts

1、undefined

2、null

2. Simple difference

3. Form of expression

1、typeof

2. == and ===

3、Object.prototype.toString.call

4. + operation and Number()

5、JSON.stringify

6、let undefiend = 'test'

4. Recommendations


foreword

The difference between undefined and null is a common topic. Before, I only understood the difference between the two. For example, when both are converted to Boolean type, they are both false, true when using == for comparison, and when using === for comparison. false, etc., without really systematically summarizing the difference between the two.

One day, a few minutes before leaving get off work, I thoroughly understood the difference between undefined and null.

1. Basic Concepts

1、undefined

undefined is a property of the "global object". That is, it is a variable in the global scope (expand the assignment to undefined variables below). The initial value of undefined is the primitive data type undefined.

2、null

null is a literal, and unlike undefined, it is not a property of the "global object". null is a missing identity, indicating that the variable does not point to any object. It may be better understood to treat null as an object that has not yet been created. In APIs, null is often used to indicate that the return type should be an object, but there is no such a value associated with a concrete object.

2. Simple difference

In general, both null and undefined mean nothing, the main difference being that undefined means the value of a variable that has not been initialized, while null means that the variable is intentionally missing an object to point to.

  • undefined

    • This variable is fundamentally undefined.

    • Hidden null value.

  • null

    • Although this value is defined, it does not point to any object in memory.

    • Declarative null value.

Below is a classic picture to help us understand.

3. Form of expression

What are the different expressions of undefined and null in JavaScript? Understanding these expressions can help us better understand the difference between undefined and null.

1、typeof

console.log(typeof undefined);   // 'undefined'
console.log(typeof null);   // 'object'

Typeof null as object is a legacy issue that cannot be fixed until now.

In the initial version of JavaScript, values ​​were stored in 32 bits. The first 3 bits represent the flag of the data type, and the remaining bits represent the value.
For all object types, its first 3 bits are marked with 000 as the type. In earlier versions of JavaScript, null was considered a special value to correspond to a null pointer in C, but JavaScript has no concept of pointers in C, so null means nothing or void and ends with all 0s (32-bit )Express.

So whenever JavaScript reads null, its first 3 bits treat it as an object type, which is why typeof null returns object.

2. == and ===

console.log(null == undefined);   // true
console.log(null === undefined);   // false
console.log(!!null === !!undefined);   // true

I believe everyone understands this point, == compares values, and === compares values ​​and types. The boolean values ​​of undefined and null are both false, so when compared with ==, it is true; while undefined and null are of different types, so they are false when compared with ===.

3、Object.prototype.toString.call

console.log( Object.prototype.toString.call(undefined) );   // '[object Undefined]'
console.log( Object.prototype.toString.call(null) );   // '[object Null]'

toString() is the prototype method of Object. When this method is called, it returns the [[Class]] of the current object by default. This is an internal property with the format [object Xxx], where Xxx is the type of the object.

So since in JavaScript, everything is an object, why can't xxx.toString() return the variable type?

This is because toString() is overridden in each class, so you need to call toString() in Object, and you must use toString.call() to call. For Object objects, [object Object] can be returned by calling toString() directly; for other objects, it needs to be called by call / apply to return the correct type information.

4. + operation and Number()

let a = undefined + 1;
let b = null + 1;
console.log(a);   // NaN
console.log(b);   // 1

console.log(Number(undefined));   // NaN
console.log(Number(null));   // 0

This involves implicit type conversion in JavaScript, which attempts to convert the variable in the expression to type number before performing the addition operation. For example: '1' + 1 will get the result 11.

  • When null is converted to a number, it will be converted to 0.

  • When undefined is converted to a number, it is converted to NaN.

5、JSON.stringify

console.log( JSON.stringify({a: undefined}) );   // '{}'
console.log( JSON.stringify({b: null}) );   // '{b: null}'
console.log( JSON.stringify({a: undefined, b: null}) );   // '{b: null}'

JSON will delete the key corresponding to undefined because of the conversion principle of JSON itself. In the case of undefined, there is no difference in the presence or absence of this piece of data, because they are not different in terms of representation.

let obj1 = { a: undefined };
let obj2 = {};

console.log(obj1.a);   // undefined
console.log(obj2.a);   // undefined

6、let undefiend = 'test'

function test(params) {
    let undefined = 'test';   // 该作用域内undefined为一个变量,赋值为test
    return params === undefined;
}

test();   // false
test(undefined);   // false
test('test');   // ture

let undefined = 'test';   // Uncaught SyntaxError: Identifier 'undefined' has already been declared

JavaScript's restriction on undefined creates a read-only undefined globally, but does not completely prohibit the definition of local undefined variables.

Please do not overwrite undefined variables at any time, even if your JSON conversion converts undefined to '', do not do it through this operation, it will be extremely dangerous behavior.

4. Recommendations

If you need to use undefined to define a null value, do not do either of the following:

  • let a;

  • let a = undefined;

And then explicitly declare undefined in the following way:

  • let a = void 0;

Guess you like

Origin blog.csdn.net/qq_41809113/article/details/123034018