Testing if a Javascript variable is definedTesting 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:

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.

Comments

blog comments powered by Disqus