Geeks With Blogs

News My Blog has been MOVED to https://mfreidge.wordpress.com
Michael Freidgeim's OLD Blog My Blog has been MOVED to https://mfreidge.wordpress.com

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 on Wednesday, October 22, 2008 12:03 AM CSS/DHTML/JavaScript | Back to top


Comments on this post: My Javascript Tips

# re: My Javascript Tips
Requesting 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).
Left by Michael Schall on Oct 24, 2008 12:28 AM

# re: My Javascript Tips
Requesting 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.


Left by Jd on Oct 24, 2008 3:38 AM

# re: My Javascript Tips
Requesting 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.
Left by Michael Freidgeim on Oct 25, 2008 2:22 AM

Your comment:
 (will show your gravatar)


Copyright © Michael Freidgeim | Powered by: GeeksWithBlogs.net