More Loops

Begin Programming with JavaScript More Loops

There’s another kind of loop called the while loop. We can use a while loop to repeat the entire program, so the user can keep using the program without restarting it.

the code

We will borrow the code from the previous chapter.

Make a new copy of the chapter-4 folder, and rename it to chapter-5a:

chapter-4
chapter-5a

Because we will create three different programs in this chapter, we are calling this first folder chapter-5a.

We will wrap the entire program in a while loop. A while loop is simpler than a for loop. All we need in the header is just a condition.

while(true){ // ← NEW

  let userInput = prompt("Please enter the numbers:");
  let inputItems = userInput.split(' ');

  let sum = 0;

  for(let i = 0; i < inputItems.length; i++){
    let num = parseInt(inputItems[i]);
    if(!isNaN(num)){
      sum = sum + num;
    }
  }

  var outputMessage = "The sum is " + sum + ".";
  alert(outputMessage);

} // ← NEW

Setting the condition to true will keep the loop running endlessly. This behavior is called an infinite loop.

Whenever there’s an infinite loop in a program, always provide an option to end the loop. In this program, when the user doesn’t enter anything, it’s safe to assume that they want to end the program.

So let’s break out of the while loop when we detect an empty input. We just have to put a conditional right after the prompt statement.

while(true){

  let input = prompt("Please enter the numbers:");

  // NEW ↓
  if(input === ""){
    break;
  }
  ...

unpack:

If the input is equal to an empty string, we stop the loop with the break keyword.

A while loop is more useful than a for loop when you don’t know how many repetitions you need, such as repeating the same program until the user wants to stop.

While VS For

The while loop is a simple and versatile tool. We can use a while loop to do the same thing that a for does.

Make a new copy of the chapter-5a folder, and rename it to chapter-5b:

chapter-5a
chapter-5b

Remove all the code in main.js. We’re starting from scratch.

For example, here’s a simple for loop that goes through an array and displays each item one by one.

let items = [1,2,3,4,5];
for(let i=0; i<items.length; i++){
  alert(items[i]);
}

Using a while loop, we can produce the same output:

let items = [1,2,3,4,5];
let i=0;
while(i<items.length){
  alert(items[i]);
  i++;
}

Here’s a side-by-side comparison:

right

unpack:

When using a while loop, we have to move the first part of the header out of the loop and move the last part inside the body of the loop.

A for loop is a convenient shortcut for working with array. It gathers everything in the header. In contrast, a while loop spreads them all over the place.

This example is only meant to illustrate the flexible and multipurpose nature of the while loop. In practice, the for loop is probably more useful than the while loop if you’re working with arrays.

Nested Loop

Make a new copy of the chapter-5b folder, and rename it to chapter-5c:

chapter-5b
chapter-5c

Remove all the code in main.js.

For this next program, we will put a for loop inside another for loop. A typical use case for this setup is working with a two-dimensional array. ↓

let table = [
  [1, 2, 3, 4, 5 ],
  [6, 7, 8, 9, 10],
  [11,12,13,14,15]
];

↑ This table variable is an array of arrays, and it’s formally referred to as a two-dimensional array (or just 2D array for short).

image

When working with a 2D array, we have to use two loops, one inside another, to go through all the items in the array.

let table = [
  [1, 2, 3, 4, 5 ],
  [6, 7, 8, 9, 10],
  [11,12,13,14,15]
];
let sum = 0;
for(let i=0; i<table.length; i++){
  for(let j=0; j<table[i].length; j++){
    sum = sum + table[i][j];
  }
}
alert(sum);

unpack:

This program is adding up all the numbers in the table array.

↓ The outside loop is for going through each sub-array in the main array, while the inside loop is for going through each item in each sub-array.

unpack:

table[i] represents each sub-array in the main array.

table[i][j] refers to each item in a sub-array.

This is a usual sticky point for beginners, so feel free to take some time to wrap your head around this concept.

↓ The 2D array is like a table and each sub-array is like a row in the table. The i and j variables are the row number and column number of each cell in the table.

image

console

To see how i and j change over time, we can print the values of i and j using the console.log function. This function is for displaying values in the console.

...
for(let i=0; i<table.length; i++){
  for(let j=0; j<table[i].length; j++){
    console.log(i, j); // NEW
    sum = sum + table[i][j];
  }
}
...

Previously, we’ve used the console as a way to experiment with code one line at a time. The console can also be used as a backstage output for the programmer, so the programmer has a way to understand how a certain variable is changing at a specific line.

The console.log function is for assisting the programmer to do their job, and it should not be part of the final program. However, it’s a helpful learning tool for beginners.

To see what’s printed out in the console. Open the program in the Chrome browser, right click on the empty page and choose inspect. ↓

image

Then choose console on the menu. ↓

image

If we plot these data on a graph, we can see how i and j change through the double-loop structure:

image

Exercise

Try to rewrite the 2D array program with two while loops.

let table = [
  [1, 2, 3, 4, 5 ],
  [6, 7, 8, 9, 10],
  [11,12,13,14,15]
];
let sum = 0;
for(let i=0; i<table.length; i++){
  for(let j=0; j<table[i].length; j++){
    console.log(i, j);
    sum = sum + table[i][j];
  }
}
alert(sum);

Solution

let table = [
  [1, 2, 3, 4, 5 ],
  [6, 7, 8, 9, 10],
  [11,12,13,14,15]
];
let sum = 0;
let i = 0; // NEW
while(i<table.length){  // CHANGE
  let j = 0;  // NEW
  while(j<table[i].length){ // CHANGE
    console.log(table[i][j]);
    sum = sum + table[i][j];
    j++; // NEW
  }
  i++; // NEW
}
alert(sum);