skip to Main Content

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


  1. You are calling yourself here before you console.log: if (looprun < 5) { myLoop(); – it works as a recursive loop

    also you add TWO to the counter with looprun += 1; AND looprun++; which is how you end up with 6

    Fixed by moving stuff around

    var looprun = 0;
    
    function myLoop() {
      looprun++;
      console.log(looprun);
      if (looprun === 4) {
        console.log("End of Loop Reached")
        return; // stop
      }
      myLoop();
    }
    
    
    myLoop();

    Alternatively use a for loop, which is made for this

    function myLoop(from, to) {
      for (let i = from; i <= to; i++) { // initial value; while this is true; change counter (increment by 1 here)
        console.log(i);
      }
    }
    myLoop(1, 4);
    
    console.log("----------------------");
    
    // alternative because we like to loop from 0 in JavaScript:
    
    for (let i = 0; i < 4; i++) {
      console.log(i + 1);
    }
    Login or Signup to reply.
  2. There are two problems in your approach.

    1. You’re double incrementing your variable.
      1. You have this line: looprun += 1;
      2. And this line: looprun++;
      3. So remove one of them.
    2. Secondly, you’re checking 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!
    3. Finally, 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:

    var looprun = 0;
    
    function myLoop() {
      looprun++;
      console.log(looprun);
      if (looprun === 4) {
        console.log("End of Loop Reached")
        return null; // break if for loop; // come out of the loop.
      }
      myLoop();
    }
    
    
    myLoop();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search