I’m trying to update a variable that exists outside of a loop from within the loop like this:
var firstRun = true;
console.log("firstRun is " + firstRun);
if(firstRun == true){
console.log("This is your first run");
firstRun = false;
}else{
console.log("You have already run this loop at least once");
};
Assuming this code block is within a larger one that would run 4 times I would expect it to output This is your first run once, then You have already run this loop at least once three times. Instead I get This is your first run 4 times and the console.log("firstRun is " + firstRun); always outputs true
I’m sure this is an issue with scope that I don’t quite understand. Forgive me, I come from the land of Ruby 🙂
You are redeclaring
firstRunevery step in the loop. Movevar firstRun = true;out of the loop.If you can’t move it out of the loop, you’ll have to use an object, and check if it’s been declared before assigning the object: