Possible Duplicate:
Detecting an undefined object property in JavaScript
From the below JavaScript sample,
try { if(jsVar) { proceed(); } } catch(e) { alert(e); }
this jsVar is declared and initialized in another file.
The problem is that code throws undefined error when this code is executed before the other file (where its declared and initialized) is executed. That is why it is surrounded by try and catch.
What's the best way to handle this undefined error than try catch?
myVariable is declared and not yet assigned with a value. Accessing the variable evaluates to undefined . An efficient approach to solve the troubles of uninitialized variables is whenever possible assign an initial value. The less the variable exists in an uninitialized state, the better.
The Boolean value of undefined is false.
typeof variable === “undefined” in JavaScript. Undefined comes into a picture when any variable is defined already but not has been assigned any value. Undefined is not a keyword. A function can also be undefined when it doesn't have the value returned.
You will get undefined value when you call a non-existent property or method of an object. In the above example, a function Sum does not return any result but still we try to assign its resulted value to a variable. So in this case, result will be undefined.
You can check the fact with
if (typeof jsVar == 'undefined') { ... }
As is often the case with JavaScript, there are multiple ways to do this:
typeof foo !== 'undefined' window.foo !== undefined 'foo' in window
The first two should be equivalent (as long as foo
isn't shadowed by a local variable), whereas the last one will return true
if the global varible is defined, but not initialized (or explicitly set to undefined
).
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