Explanation of the usage of null and undefined in js---from "Writing maintainable javascript"

1. null

null is a special value, but we often misunderstand it and confuse it with undefined. null should be used in the following scenarios:

1. Used to initialize a variable, which may be assigned an object;

2. Used to compare with an initialized variable, which may or may not be an object;

3. When the parameter of the function is expected to be an object, it is passed in as a parameter;

4. When the return expected value of the function is an object, it is used as the return value to pass out


The following scenarios should not use null:

1. Do not use null to detect whether a parameter is passed in;

2. Do not use null to detect an uninitialized variable.

Sample code:

        //good usage
        var person = null;

        //good usage
        function getPerson() {
            if(condition){
                return new Person("Jack");
            }else{
                return null;
            }
        }


        //good usage
        var person = getPerson ();
        if(person !== null){
            doSomething();
        }


        // bad usage: used to compare with uninitialized variables
        was person;
        if(person !== null){
            doSomething();
        }

        //Bad writing: check if a parameter is passed in
        function doSomething(arg1, arg2, arg3) {
            if(arg4 != null){
                doSomething();
            }
        }

The best way to understand null is as a placeholder for an object, a rule not mentioned in any mainstream programming norm, but essential for global maintainability.


二、undefined

undefined is a special value that we often confuse with null. One of the confusing things is that null == undefined is true. However, these two values ​​are used for different purposes. Those variables that have not been initialized have an initial value, that is, undefined, which means that the variable is waiting to be assigned a value.

       // bad spelling
        was person;
        console.log(person === undefined);//true

Although this code works fine, I recommend avoiding undefined in your code. This value is often confused with the typeof operator returning "undefined". In fact, the behavior of typeof is also puzzling. Because whether the value is an undefined variable or an undeclared variable, the result of the typeof operator is undefined.

By disallowing the special value undefined, you effectively ensure that typeof will return undefined only in one case: when the variable is undeclared. If you use a variable that may (or may not) be assigned to an object, assign it to null.

Assigning a variable to null indicates the intent of the variable, which is likely to end up being an object. The typeof operator returns "object" when the type is null. This can be distinguished from undefined.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325849281&siteId=291194637