The Linux Page

JavaScript and undefined variables

As I create website, I often deal with JavaScript code. At times, a variable doesn't make it for different reasons, for instance a part is missing and thus the variable generation doesn't happen. If then the script uses that undefined variable, then it generates an error. In some cases, it may not matter too much. However, when the variable that doesn't exist is hit, the JavaScript interpreter generates an exception and stops the execution of the script altogether (unless you capture the exceptions... Do you do that?!)

The solution is to test the variable and since I always have to search how to write that code, I decided to write it here:

  if ( typeof ( myvar ) != "undefined" ) { /* here you can use the variable safely! */ }

Note that the correct syntax should have been:

  if ( myvar != undefined ) { ... }

However, the JavaScript specification in that regard has not be followed by everyone... and thus the undefined special keyword is not recognized across the board, hence the 1st working syntax.