Sunday, January 17, 2010

JavaScript: The difference between null and undefined

JavaScript is different from other programming languages by containin both undefined and null values, which may cause confusion.

null is a special value meaning "no value". null is a special object because typeof null returns 'object'.

On the other hand, undefined means that the variable has not been declared, or has not been given a value.

Following snippets display 'undefined':

// x is not declared anywhere in code
alert(typeof x);


var x;
alert(typeof x);

Although null and undefined are slightly different, the == (equality) operator considers them equal, but the === (identity) operator doesn't.

No comments:

Post a Comment