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

Advertisements