Javascript - Checking if a variable is defined
The following is taken from this page.
....
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.
0 Comments:
Post a Comment
<< Home