What is the difference between null and undefined in JavaScript?

前端 未结 30 3274
夕颜
夕颜 2020-11-21 23:06

I want to know what the difference is between null and undefined in JavaScript.

30条回答
  •  再見小時候
    2020-11-21 23:51

    tl;dr

    Use null for set a variable you know it is an Object.

    Use undefined for set a variable whose type is mixed.


    This is my usage of both 5 primitives and Object type, and that explain the difference between « use case » of undefined or null.

    String

    If you know a variable is only a string while all lifecycle, by convention, you could initialize it, to "":

    ("") ? true : false; // false
    typeof ""; // "string";
    ("Hello World") ? true : false; // true
    typeof "Hello World"; // "string"
    

    Number

    If you know a variable is only a number while all lifecycle, by convention, you could initialize it, to 0 (or NaN if 0 is an important value in your usage):

    (0) ? true : false; // false
    typeof 0; // "number";
    (16) ? true : false; // true
    typeof 16; // "number"
    

    or

    (NaN) ? true : false; // false
    typeof NaN; // "number";
    (16) ? true : false; // true
    typeof 16; // "number"
    

    Boolean

    If you know a variable is only a boolean while all lifecycle, by convention, you could initialize it, to false:

    (false) ? true : false; // false
    typeof false; // "boolean";
    (true) ? true : false; // true
    typeof true; // "boolean"
    

    Object

    If you know a variable is only an Object while all lifecycle, by convention, you could initialize it, to null:

    (null) ? true : false; // false
    typeof null; // "object";
    ({}) ? true : false; // true
    typeof {}; // "object"
    

    Note: the smart usage off null is to be the falsy version of an Object because an Object is always true, and because typeof null return object. That means typeof myVarObject return consistent value for both Object and null type.

    All

    If you know a variable has a mixed type (any type while all lifecycle), by convention, you could initialize it, to undefined.

提交回复
热议问题