Simple: check if variable exists

I am trying to find out how to check if a variable exists or not to prevent an error if you use it when it’s not defined.

This is what I thought would work:


if (typeof varName === 'undefined') {}

… But I get a ‘could not get the type property’ error in IE6 and decent browsers still say the variable isn’t defined.

I’m pretty certain for an object you can just do:


if(object) {

}

…but not with vars.

So what is the best (all browser) way to check if a variable is defined?

The above code you posted should work fine in all browsers as it’s been standard in the ECMA JavaScript spec since the IE6 and probably even before then, there is nothing to suggest the above wouldn’t work.

Sorted, thanks.

Browser was caching my old JS file.

Thanks!