What is the difference between null and undefined in JavaScript?

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

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

30条回答
  •  清歌不尽
    2020-11-21 23:53

    For the undefined type, there is one and only one value: undefined.

    For the null type, there is one and only one value: null.

    So for both of them, the label is both its type and its value.

    The difference between them. For example:

    • null is an empty value
    • undefined is a missing value

    Or:

    • undefined hasn't had a value yet
    • null had a value and doesn't anymore

    Actually, null is a special keyword, not an identifier, and thus you cannot treat it as a variable to assign to.

    However, undefined is an identifier. In both non-strict mode and strict mode, however, you can create a local variable of the name undefined. But this is one terrible idea!

    function foo() {
        undefined = 2; // bad idea!
    }
    
    foo();
    
    function foo() {
        "use strict";
        undefined = 2; // TypeError!
    }
    
    foo();
    

提交回复
热议问题