SgtWilliams
SgtWilliams

Reputation: 35

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");
	}
}

Upvotes: 0

Views: 131

Answers (1)

Quentin
Quentin

Reputation: 943601

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.

Upvotes: 7

Related Questions