I want to know what the difference is between null
and undefined
in JavaScript.
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'