This makes me feel stupid now, but I am trying to work on a simple counting loop in Javascript – one that starts with a variable set at 0 and then adds one to it for every iteration of the loop.
The problem is that when I run it, I would expect it to print
1
2
3
4
but it instead prints 6 two times, which I find really confusing because I haven’t even mentioned anything about 6. In addition to this, it doesn’t print End of Loop Reached
either. Any help as to why this is happening would be useful.
var looprun = 0
function myLoop() {
looprun += 1;
looprun++;
if (looprun < 5) {
myLoop();
console.log(looprun)
}
if (looprun == 4) {
console.log("End of Loop Reached")
}
}
myLoop();
2
Answers
You are calling yourself here before you console.log:
if (looprun < 5) { myLoop();
– it works as a recursive loopalso you add TWO to the counter with
looprun += 1;
ANDlooprun++;
which is how you end up with 6Fixed by moving stuff around
Alternatively use a for loop, which is made for this
There are two problems in your approach.
looprun += 1;
looprun++;
looprun < 5
and if it’s true, you’re immediately before printing the value, sending it to the run the next iteration, so your log never runs!if (looprun == 4) {
this will always be false, because when your code control reaches here, the value will always be 5 or over that!My solution for this is: