Why is null an object and what's the difference between null and undefined?

后端 未结 22 1039
猫巷女王i
猫巷女王i 2020-11-22 02:58

Why is null considered an object in JavaScript?

Is checking

if ( object == null )
      Do something

the

22条回答
  •  既然无缘
    2020-11-22 03:52

    The following function shows why and is capable for working out the difference:

    function test() {
            var myObj = {};
            console.log(myObj.myProperty);
            myObj.myProperty = null;
            console.log(myObj.myProperty);
    }
    

    If you call

    test();
    

    You're getting

    undefined

    null

    The first console.log(...) tries to get myProperty from myObj while it is not yet defined - so it gets back "undefined". After assigning null to it, the second console.log(...) returns obviously "null" because myProperty exists, but it has the value null assigned to it.

    In order to be able to query this difference, JavaScript has null and undefined: While null is - just like in other languages an object, undefined cannot be an object because there is no instance (even not a null instance) available.

提交回复
热议问题