What is the difference between null and undefined in JavaScript?

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

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

30条回答
  •  借酒劲吻你
    2020-11-21 23:28

    In JavaScript, undefined means a variable has been declared but has not yet been assigned a value, such as:

    var TestVar;
    alert(TestVar); //shows undefined
    alert(typeof TestVar); //shows undefined
    

    null is an assignment value. It can be assigned to a variable as a representation of no value:

    var TestVar = null;
    alert(TestVar); //shows null
    alert(typeof TestVar); //shows object
    

    From the preceding examples, it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

    null === undefined // false
    null == undefined // true
    null === null // true
    

    and

    null = 'value' // ReferenceError
    undefined = 'value' // 'value'
    

提交回复
热议问题