Loops Cheat Sheet

How can we tell how many times a loop will execute?

We have to look at it's starting value, and its limit.


      
      var i = 0; 
      while (i < 5) {
      
      console.log(i);
      i = i + 1;
      }
      
    

In the code above, the starting value is 0, and the limit is reached when the counter is no longer LESS THAN 5.

This means that as soon as the counter reaches 5, the loop will stop.

And the loop does run 5 times, and it prints 5 numbers. Let's count:


      0 (1st time)
      1 (2nd time)
      2 (3rd time)
      3 (4th time)
      4 (5th time)
    
The tricky piece here is that since we started with 0, the 5th number will actually be 4.

So if the loop uses LESS THAN, the formula is: Limit minus starting value = number of times the loop will run.

Let's look at this code, how many times will it run?


      
      var i = 3; 
      while (i < 4) {
      
      console.log(i);
      i = i + 1;
      }
      
    

According to our formula, it should be 4 minus 3, which is 1. Let's see what it does.


      
    3
    
    

LESS THAN or EQUAL TO (<=)

But what if the while loop uses <= ?


      
      var i = 3; 
      while (i <= 4) {
      
      console.log(i);
      i = i + 1;
      }
      
    

Now the output is:


      
    3
    4
    
    

So we can use a variation of our formula: Limit plus 1 minus starting value = number of times the loop will run.

Lastly, it's important to note that even though we can always tell how many times the loop will run, depending on where we put the command to print, the loop will output different things. In the code below, the only difference is that we switched the last 2 lines


      
      var i = 3; 
      while (i <= 4) {
      
      i = i + 1;
      console.log(i);
      }
      
    
But now it outputs:

      
    4
    5