What is the difference between null and undefined in JavaScript?

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

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

30条回答
  •  清酒与你
    2020-11-21 23:31

    OK, we may get confused when we hear about null and undefined, but let's start it simple, they both are falsy and similar in many ways, but weird part of JavaScript, make them a couple of significant differences, for example, typeof null is 'object' while typeof undefined is 'undefined'.

    typeof null; //"object"
    typeof undefined; //"undefined";
    

    But if you check them with == as below, you see they are both falsy:

    null==undefined; //true
    

    Also you can assign null to an object property or to a primitive, while undefined can simply be achieved by not assigning to anything.

    I create a quick image to show the differences for you at a glance.

提交回复
热议问题