Thursday, May 17, 2007

Javascript undefined vs. null

In JavaScript, 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

From the preceding examples, it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

Unassigned variables are initialized by JavaScript with a default value of undefined.

JavaScript never sets a value to null. That must be done programmatically. As such, null can be a useful debugging tool. If a variable is null, it was set in the program, not by JavaScript.

null values are evaluated as follows when used in these contexts:

Boolean: false
Numeric: 0
String: “null”

undefined values are evaluated as follows when used in these contexts:

Boolean: false
Numeric: NaN
String: “undefined”

.........................................................................................................................................................

null is an object. It's type is null. undefined is not an object, it's type is undefined.

Use if (SomeObject) to check value existence is not robust. It will also catch the cases of SomeObject having numeric value of 0, or string value of empty string. Because their boolean coercion is also false. See, in JavaScript, null and undefined are actually equal according to the == and != operator! (ECMA-262 standard, section 11.9.3 tells us so.) So we have null == undefined. In vast majority of cases, you don't care about the difference at all, so using someExpr != null is good enough.

If we really need to differentiate null and undefined, use

typeof(SomeObject) == 'undefined'

No comments: