Reputation: 473
I have this javscript that I wrote, and I want the "else" event to happen when bgimage does not equal 7. I have looked into this issue and am unclear about how to check if the variable is null or not defined. Currently, when bgimage does not equal 7, the Firebug just says "bgimage is not defined."
Thanks for teaching me how to do this in advance.
if (bgimage == 7)
{
document.writeln("\n<img src='/v/vspfiles/templates/donnell/images/Company/services_bg.jpg' id='bg' />");
}
else
{
showImage();
}
Upvotes: 0
Views: 56
Reputation: 28554
You can test if a variable is undefined by using typeof
, then combine that with your original condition:
if (typeof(bgimage) != "undefined" && bgimage == 7)
So now the else
section of your code will be used if bgimage is undefined, or if it is defined, but not equal to 7.
Upvotes: 0
Reputation: 150000
If bgimage
has not been declared with var
in the current or higher scope (or assigned a value as a global variable without var
) when you use it in an if
statement you will get that error. You can test for that as follows:
if (typeof bgimage === "undefined") {
// hasn't been declared, or is set to undefined
// do something
} else if (bgimage == 7) {
// etc
Or test in one line:
if (typeof bgimage != "undefined" && bgimage == 7) {
Upvotes: 0
Reputation: 700152
Check the type of the variable to determine if it is undefined:
if (typeof bgimage != 'undefined' && bgimage == 7)
Upvotes: 2