SgtWilliams SgtWilliams - 2 months ago 6
Javascript Question

Call a variable in an if-statement inside a function

Hello I've got the problem that I can't call the variable

imgNotSet
in my if-statement of the
openImage
function. My Question is do I need to give my variable another scope to call it or what did I do wrong?



var imgNotSet = true;

function openImage() {
if (imgNotSet) {
var lightViewImg = document.createElement("IMG");
document.body.appendChild(lightViewImg);
document.getElementsByTagName("img")[0].setAttribute("src","imgplaceholder");
var imgNotSet = false;
} else {
console.log("Img already set");
}
}




Answer

My Question is do I need to give my variable a special scope to call it

No. You are doing that already and that is the problem.

var imgNotSet = false;

You've created another variable of the same name, but locally scoped to the function, here. Don't do that. Remove the var.