My Javascript Tips

Check if object is null or undefined.

I had an understanding that to check if variable not null in JavaScrip, you need to check

if (typeof SomeObject !='undefined') .

But it is wrong, because null is not the same as 'undefined'.

From http://weblogs.asp.net/bleroy/archive/2005/02/15/Three-common-mistakes-in-JavaScript-_2F00_-EcmaScript.aspx

The shortest way to deal with this, and also the one that best expresses your intention of checking if an object is safe to use is probably to just rely on the type-sloppiness of JavaScript and count on it to evaluate null and undefined as false in a boolean expression, like this:

if
(SomeObject.foo) {

My other Javascript related posts:

Javascript variable declaration scope is different from C#.

Javascript to re-calculate summary based on user drop-down lists selections

Differences in Internet Explorer and FireFox CSS and Javascript

Helper function to Print Page using JScript(including inside frame)

My JScriptHelper class

posted @ Wednesday, October 22, 2008 12:03 AM

Print

Comments on this entry:

# re: My Javascript Tips

Left by Michael Schall at 10/24/2008 12:28 AM
Gravatar
You need to be very careful with this shortcut however. Make sure that the foo you are checking is indeed an "object" or know the "falsey" rules for all types.

if (SomeObject.foo) {

This code will return false if foo == 0, foo == '' (empty string), foo == [] (empty array), foo == false. Am I missing one?

If you want to check if foo is null or undefined, you can check if (SomeObject.foo == null). If you only want to check for null, use if (SomeObject.foo === null).

# re: My Javascript Tips

Left by Jd at 10/24/2008 3:38 AM
Gravatar
You have to be careful. What if value of foo is boolean and has value of 'false'? Only safe way to verify is using 'typeof'. Look at isValue function in YUI library.


# re: My Javascript Tips

Left by Michael Freidgeim at 10/25/2008 2:22 AM
Gravatar
Michael and Jd,
Thank you for pointing that the check is applicable for real OBJECTS.
I am usually check if control exists in DOM, and for these cases it is good enough.
I will look at http://developer.yahoo.com/yui/ library.

Your comment:



 (will not be displayed)


 
 
 
 
 

Live Comment Preview:

 
«November»
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345