Safest way to check an object exists in JavaScript

Had to note this down somewhere. How to tell if an object is null or undefined.

if (!! foo) alert('foo is defined and not-null');
if (! foo) alert('foo is undefined or null');

or if you want to test an method or value that might return NaN, 0, zero-length string, or of course false is not null you can use

if (typeof(SomeObject)!="undefined")

And there is nothing wrong with the following if you don’t want to distinguish between null and undefined.

if(SomeObject != null)

Thanks to this post and it’s comments for all the tips.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: