Differences Between Null and Undefined in JavaScript

When we design a site using JavaScript,we will find there are two original types : null and undefined.Now we maybe puzzle when to use null and when to use undefined.

Null type is only one value ,just is null.It is used to indicate a not exist object.Commonly used to express a not exist object function attempts to return .

Undefined type is also only one value ,just is undefined.When a declared variable is not been initialized, the default value of the variable is undefined.

Javascript code

var Value1;
alert(Value1 == undefined);

The code will output true.It mean the value of Value1 is undefined because we have not initialized Value1.

Javascript code

alert(null == document.getElementById('notExistElement'));

When DOM node id of "notExistElement" is not exist on the page, the code will output true, because we try to obtain a non-existent object.

Javascript code

alert(typeof undefined); 
alert(typeof null); 

The first code will output undefined.But the second code will output object,why ?In fact, this is an error initially implemented in JavaScript.We can explain the null is the placeholder object that does not exist.

Javascript code

alert(null == undefined); 

ECMAScript consider undefined is derived from null so this code will output true.But how can we distinguish the two types?We can use the two ways following.

Javascript code

alert(null === undefined);
alert(typeof null == typeof undefined);

Both of them will output false.The types of them are different so it outputs false.



This address is http://www.computerites.com/web-design-skills/2012/12/differences-between-null-and-undefined-in-java-script-625.html