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();
}
Subscribe!
If you found this post interesting and would like to be notified the next time something is posted, please subscribe to my RSS Feed. Thanks for visiting!
