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.

INCORRECT

This will work.

<script> var a=1; if(a) alert('a='+a); else alert('"a" what?!'); </script>

This will fail AND THROW AN ERROR.

(Meaning, it WILL NOT run the else case.) <script> /* var a=1; */ if(a) alert('a='+a); else alert('"a" what?!'); </script>

CORRECT

This will work.

<script> window.a = 1 if(window.a) alert('window.a='+a); else alert('that\'s crazy talk'); </script>

This will fail BUT WILL NOT THROW AN ERROR.


(It will fail in a controlled way. Meaning, it WILL run the else case.) <script> /* window.a = 1 */ if(window.a) alert('window.a='+a); else alert('that\'s crazy talk'); </script>

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