Knowledge Base Articles » KB100208: Shedding Light on the JavaScript Special Values null and undefined.

JavaScript, unlike VBScript, does not provide a function to test for null. This article defines the special values null and undefined and provides some examples of how to test for them in JavaScript.

A special value given to variables after they are created and before a value has been assigned to them.

A value indicating that a variable contains no valid data. null is the result of either:
1) An explicit assignment of null to a variable; or
2) An operation between expressions that contain null.

If a variable is null or undefined, the variable will evaluate to false.

With this said, if you do not use null in your code, you need not test for it. If you do wish to filter out null and undefined variables you should use the "if(x)" test below.

var x
if (x) //x is undefined therefore this will evaluate to false

var x
x = null
if (x) //x is null therefore this will evaluate to false

Conversely, the "if (!x)" test will only succeed if x is either null or undefined.

To explicitly test for the undefined value you should use:
if (vartype(x) == undefined)

To explicitly test for the null value you should use:
if (x == null)

Try running this code:

<script type="text/javascript">
var x;
if( x == undefined )
   alert("x is undefined");
   alert("x is defined");
var y;
y = null;
if( y == null )
   alert("y is null");
   alert("y is not null");