Submodule 7.2: Loops

  • for loop
  • while loop

while loop

We use while loops when we don’t know how many times we want it to run.

The while loop has the following syntax:

while (condition) {
code block to be executed
}

The while loop, loops through a block of code as long as a specified condition is true.

Example 1
/* add consectuive integers until we get to 100*/
var i = 0, sum = 0;
while(sum <= 100){
    /*here we increment i, then add it to sum*/
    i = i + 1;
    sum = sum + i;
}
/*the loop exits when sum reaches or exceeds 100*/
console.log("We added up to "+i+" to get to 100");

This example uses a while loop to add consecutive integers until the sum equals or exceeds 100. The while condition tests if this is true, and at each loop it increments i and adds it to sum. The while loop works well here since we don't know how many times the loop will have to run.

Tip: Copy the above piece of code and paste it directly into the console, to see how it works.

In this spreadsheet, you can see the values of the variables

For more information:
https://www.w3schools.com/js/js_loop_while.asp

JavaScript while loop
JavaScript for loop

Exercise

Add odd consecutive integers until the sum equals or exceeds 1000.What is the last number you added up?

Solution:

var j = 0;
var sum = 0;
while (sum < 1000) {
  j = j + 1;
  if (j % 2 == 1){
      sum = sum + j;
  };
};
console.log(j)