What is the difference between null and undefined in JavaScript?

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

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

30条回答
  •  别跟我提以往
    2020-11-21 23:29

    In JavasSript there are 5 primitive data types String , Number , Boolean , null and undefined. I will try to explain with some simple example

    lets say we have a simple function

     function test(a) {
    
         if(a == null){
            alert("a is null");
         } else {
            alert("The value of a is " + a);
         }
      }
    

    also in above function if(a == null) is same as if(!a)

    now when we call this function without passing the parameter a

       test(); it will alert "a is null";
       test(4); it will alert "The value of a is " + 4;
    

    also

    var a;
    alert(typeof a); 
    

    this will give undefined; we have declared a variable but we have not asigned any value to this variable; but if we write

    var a = null;
    alert(typeof a); will give alert as object
    

    so null is an object. in a way we have assigned a value null to 'a'

提交回复
热议问题