Quick References
ADO
ASP
CSS2
HTML
JavaScript
Jet SQL
VBScript
WML
WMLScript
WSH
XHTML
XML DOM
XSLT
Features
Knowledge Base
Tutorials
Partners
ZVON.ORG
XML
Planet Source Code
VisualBuilder
Web Design
Your HTML Source
XML/XSLT Forums
ASPAlliance
Scripts
Programmers Heaven
Tek-Tips Forums
Developer Fusion
Code Project
A100208: 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.
undefined:
A special value given to variables after they are created and before a value has been assigned to them.
null:
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:
<html>
<body>
TEST START
<br>
<script type="text/javascript">
var x;
if( x == undefined )
alert("x is undefined");
else
alert("x is defined");
var y;
y = null;
if( y == null )
alert("y is null");
else
alert("y is not null");
</script>
<br>
TEST END
</body>
</html>
The Guru
Copyright 1999-2005 by Infinite Software Solutions, Inc. All rights reserved.
Trademark Information
knoxville photographer
knoxville wedding photographer