Friday, November 15, 2013

undefined and null in javascript. What is the difference ?

There is one difference between undefined And null in JavaScript undefined is a data type and null is a value.


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


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

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

Like

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

var a = ''  ;
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 undefined 

Now it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

Related Posts Plugin for WordPress, Blogger...

Receive all updates via Facebook. Just Click the Like Button Below

You can also receive Free Email Updates: