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?
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?
Share Improve this question edited Jun 30, 2009 at 11:15 Alex Rozanski 38k10 gold badges69 silver badges69 bronze badges asked Jun 30, 2009 at 11:12 NirNir 25.4k26 gold badges84 silver badges119 bronze badges 3 |2 Answers
Reset to default 14'var' is not a valid variable name - it's a keyword.
Apart from that, what you have should be correct.
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
typeof
is an operator, not a function. You don't need parentheses around the operand. [This is migrated from my answer as it is not an answer; I believe I had insufficient rep to post a comment at the time] – Tim Down Commented Feb 7, 2013 at 22:55