views:

3971

answers:

3

I have code that is wrapped in try/catch block. I use typeof to find out if a variable is defined:

if (typeof (var) == 'string') { 
    //the string is defined
}

However, using this in a try/catch block, jumps to the catch part instead of doing what it is suppoed to do (do something with the string if its defined).

How can I check if a variable is defined without activating an exception?

+7  A: 

'var' is not a valid variable name - it's a keyword.

Apart from that, what you have should be correct.

Greg
Thanks! please see my comment above
Nir
A: 

I would use a direct comparison without 'typeof':

var vvv= 2;
alert( vvv !== undefined );

Be careful, though, to know whether you want to check for truliness (not false, null, undefined, "" or 0), against null, undefined, false or a combination of these.

If you simply want to see that the value has a value, the code I placed above should do.

As a suggestion, I have found this book tremendous: JavaScript - the Good Parts

akauppi
Thanks! please see my comment above
Nir
var vvv= 2; alert( vvv !== undefined ); doesn't work in all cases. Firstly, try it without the first line, and you get an error straight away because vvv has not been declared. Secondly, and this is not anything like as important, the "undefined" on the right hand side of the comparison is a property of the global object that can be reassigned and isn't even present in some browsers (IE 5, for example). So the best test for a variable v being defined is:if (typeof v !== "undefined") { ...}
Tim Down
+1  A: 

One point: typeof is an operator, not a function. You don't need parentheses around the operand.

Tim Down