Testing if a Javascript variable is defined
Posted October 23rd, 2007 in Javascript (Updated October 23rd, 2007)
Sometimes in Javascript you need to be able to determine if a variable has already been defined before continuing with your script. It is very simple to do this using the typof operator, as show in the example below:
var has_foo = typeof foo != 'undefined';
if(has_foo) {
do_something();
}
else {
do_something_else();
}
If the "has_foo" variable in the above example was not going to be used again, then the Javascript code could be made slightly smaller, and the logic reversed:
if(typeof foo == 'undefined') {
do_something_else();
}
else {
do_something();
}
Related posts:
- Setting default values for missing parameters in a Javascript function (Tuesday, November 24th 2009)
- Using setTimeout() with Javascript (Tuesday, January 27th 2009)
- Find the index of a string within a string with Javascript (Friday, November 28th 2008)
- Opening a new window with Javascript (Saturday, November 22nd 2008)
- Javascript getYear fix (Wednesday, August 13th 2008)
- How to check if a Javascript function exists (Saturday, July 5th 2008)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

