API
@-Formulas
JavaScript
LotusScript
Reg Exp
Web Design
Notes Client
XPages
 
Checking For Global Variables
With all the reusable JavaScript code that we write, there comes some times when we have to rely on the developer using the reusable code to set up some global JavaScript variables that the code reads to determine settings. For example, there may be a time when you want to automatically generate a table and use that in several different web sites. But the table may have alternate row colors, and the values for those colors need to be set in global JavaScript variables that are read by the reusable code.

However, we have found that sometimes developers don't read the documentation on how to set up a reusable piece of code, and will omit the global JavaScript variable. So when that reusable code is executed, an error message happens because the variable has not been defined.

To get around this, we have gotten in the habit of checking to see if a variable has been defined. This is actually pretty easy to do in JavaScript, but it's not something you would normally think of. The first thing we tried was:
if (globalVariable) {

But this wouldn't work. That code is actually checking to see if the defined variable globalVariable has a null value. If the variable has not been defined, that code will cause an error.

Instead, here is the code that will check for the presence of a global variable:
if (window.globalVariable) {

A global variable automatically becomes a part of the window object. So checking to see if the window object has that "property" means checking to see if the variable has been defined or not. Going into the if block means the variable has been defined and can be used as you would normally use a global variable.