What is the difference between null and undefined in JavaScript?

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

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

30条回答
  •  遇见更好的自我
    2020-11-21 23:43

    null is a special keyword that indicates an absence of value.

    think about it as a value, like:

    • "foo" is string,
    • true is boolean ,
    • 1234 is number,
    • null is undefined.

    undefined property indicates that a variable has not been assigned a value including null too . Like

    var foo;
    

    defined empty variable is null of datatype undefined


    Both of them are representing a value of a variable with no value

    AND null doesn't represent a string that has no value - empty string-


    Like

    var a = ''; 
    console.log(typeof a); // string 
    console.log(a == null); //false 
    console.log(a == undefined); // false 
    

    Now if

    var a;
    console.log(a == null); //true
    console.log(a == undefined); //true 
    

    BUT

    var a; 
    console.log(a === null); //false 
    console.log(a === undefined); // true
    

    SO each one has it own way to use

    undefined use it to compare the variable data type

    null use it to empty a value of a variable

    var a = 'javascript';
    a = null ; // will change the type of variable "a" from string to object 
    

提交回复
热议问题