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

后端 未结 22 1507
猫巷女王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:31

    The difference can be summarized into this snippet:

    alert(typeof(null));      // object
    alert(typeof(undefined)); // undefined
    
    alert(null !== undefined) //true
    alert(null == undefined)  //true
    

    Checking

    object == null is different to check if ( !object ).

    The latter is equal to ! Boolean(object), because the unary ! operator automatically cast the right operand into a Boolean.

    Since Boolean(null) equals false then !false === true.

    So if your object is not null, but false or 0 or "", the check will pass because:

    alert(Boolean(null)) //false
    alert(Boolean(0))    //false
    alert(Boolean(""))   //false
    

提交回复
热议问题