Tag Archives: Logic

How to detect a variable existence in JavaScript?

Preface

After reading one of the latest posts from Stoyan Stefanov’s blog – phpied.com I stumbled upon an interesting construction in JavaScript describing how to check an object property existence. I’m going to cover this case using as an example the console object, which comes with the Firebug enabled, and I think it may be very useful, just because this object is widely used, but doesn’t exists over all the browsers, even under Firefox when Firebug is disabled. This construction is known as the IN statement and it looks something like that:

property in object

which I’m going to cover later in details.

How you detect a variable existence?

There are three main ways to detect the existence of a property I see in my practice.

1. The most widely used:

if ( console ) { ... }

2. The second and more professional one:

if ( typeof console != 'undefined' ) { ... }

3. And finally the third and most unknown:

if ( console in window ) { ... }

Of course two of them are wrong! Which one should be changed?

Is everything working correctly? No!

Lets see how they are working. First of all I’m going to test all of them on Firefox 3.6 either with enabled and disabled Firebug, just shouting with old school’s alert().

Now the first one using the IN statement:

if ( console in window )
   alert('object exists!');
else
   alert('object doesn\'t exists!');

With Firebug disabled the answer is … nothing! No alert! That’s because the syntax is wrong. There’s an error within the IF statement. We should modify a bit the first row like that:

if ( 'console' in window )
   alert('object exists!');
else
   alert('object doesn\'t exists!');

Now everything’s OK. With a disabled Firebug the answer is: “object doesn’t exists!”, and after enabling it, normally the “object exists!”.

Lets move on the next example:

if ( console )
   alert('object exists!');
else
   alert('object doesn\'t exists!');

With Firebug enabled the answer is as we expect: “object exists!”, but after disabling it yet again – nothing?! Why’s that? Because the console object doesn’t exists anymore and the IF statement doesn’t return true or false, but simply crashes. How to modify the code? Simply by adding a window.console instead of console.

if ( window.console )
   alert('object exists!');
else
   alert('object doesn\'t exists!');

Than the answer is: “the object doesn’t exists!” after what we expected!

The third method is the mostly used, just because it’s completely clear what’s the goal of the IF statement:

if ( typeof console != 'undefined' )
   alert('object exists!');
else
   alert('object doesn\'t exists!');

In both disabled and enabled Firebug the answer is as expected!

Now the IN statement may be used if not for the console, but for checking the existence of a property of within an object.