Javascript if typeof ='undefined' in try/catch space
-
21-08-2019 - |
Question
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?
Solution
'var' is not a valid variable name - it's a keyword.
Apart from that, what you have should be correct.
OTHER TIPS
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