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 firstRun every step in the loop. Move var 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:
var firstRun = firstRun || {ran: false};
if (firstRun.ran == true) {
console.log("This is your first run");
firstRun.ran = false;
} else {
console.log("You have already run this loop at least once");
};
I am assuming the boolean is being reset on every iteration. Move the var firstRun = true; outside the loop!
var firstRun = true;
for (...) {
if(firstRun){firstRun=false;}
else{}
}
You are resetting the firstRun variable every time in the loop, so when the conditional statement is executed the value of firstRun will always be true.
You need to do something like this
var firstRun = true;
//Loop only following block
if(firstRun == true){
console.log("This is your first run");
firstRun = false;
}else{
console.log("You have already run this loop at least once");
};
If that whole block is in your loop, you're going to reset var firstRun = true every iteration. You'll want to set var firstRun = true outside the loop (right before it for clarity).
var firstRun = true;
for (var i = 0; i < 4; i++) {
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");
};
}