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?
In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. If the value is not defined, typeof returns the 'undefined' string.
The typeof undefined is the string "undefined" — and undefined is a falsy value that is loosely equal to null but not to other falsy values.
It means null is equal to undefined but not identical. When we define a variable to undefined then we are trying to convey that the variable does not exist . When we define a variable to null then we are trying to convey that the variable is empty.
'var' is not a valid variable name - it's a keyword.
Apart from that, what you have should be correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With