Proper testing for defined JavaScript variables
I often see even seasoned programmers testing for JavaScript variables
in ways that do not fail in a controlled fashion. The current reality of JavaScript
support is such that testing for the very existence of a non-existent variable
can trigger an error. There are ways however, to use variables that fail
gracefully.
One method I favor is to test for a value as a property of a known object. For example, "window"
always exists... so as a script author I can attach properties to the window
object -- being careful not to tread over reserved names (see also naming conventions).
A nice feature of objects is that you can test for non-existent properties of
objects without triggering an error. Try the examples below by clicking the "Prove It"
button beside the example you want to run.
The JavaScript engine throws an
error differently in each browser. Here are two I use regularly under Windows.
- If you are using Internet Explorer, you may
need to go to TOOLS->INTERNET OPTIONS->ADVANCED and check the box beside
"Display a notification about every script error". (Note: this box is often
OFF by default, meaning your visitors won't see an error indication... instead
the script just wont run... which is arguably worse from a troubleshooting standpoint.
Just because the browser doesn't tell you an error happened doesn't mean that it
didn't... if you have subsequent script that needs to run it may be interfered
with by the invisible failure.)
- If you use Mozilla, you'll need to have the "javascript:" window open. (Just
enter "javascript:" as a URL and it'll pop open.)
INCORRECT
This will work.
This will fail AND THROW AN ERROR.
(Meaning, it WILL NOT run the else case.)
CORRECT
This will work.
This will fail BUT WILL NOT THROW AN ERROR.
(It will fail in a controlled way. Meaning, it WILL run the else case.)
There are other methods for error handling, including the more traditional try and catch mechanism (see also, try, catch, and throw)
Related Keywords and misspellings:
javascript, help, testing for defined javascript variables, undefined, variables, undef