Coding Practice: Loops

From reading loops to writing them

Every loop you have met so far was already written, and your job was to work out what it did. That flips now. Nobody hands you the code, only a description of what the function has to give back, and you decide what the loop looks like.
The good news is that the loops in this set are all the same shape underneath. Once you can see the shape, writing one is filling in three slots rather than inventing anything.

Three questions before you type anything

Answer these in your head, in this order, and the loop mostly writes itself.
• What am I keeping between passes? One variable, declared before the loop, changed inside it.
• What does it start as? This is the answer your function gives back when the loop never runs at all.
• What do I do with it when the loop ends? Almost always: return it.
What you are buildingStart it atThe line inside the loop
a total0add the current value to it
a count0add 1, but only when the test passes
a piece of textthe empty stringglue the next piece on with a plus sign
the largest so farthe <b>first</b> value in the arrayreplace it when you meet something bigger

Two loops that stop for a reason, not for a count

A loop does not have to walk the whole array. If you are hunting for the first thing that matches, a return inside the loop hands the value straight back to the caller and ends the loop on the spot, so everything after the match is never looked at. Remembering the position in a variable and carrying on to the end gives you the last match instead of the first, which looks identical until the data holds two of them.
And when you cannot say in advance how many passes you need, the loop is a while, and its condition is a question about the data rather than a count: while the total is still under the limit, while the number is still even, while the guess is still wrong.
The function below multiplies the numbers in an array, and the program calls it once on three numbers and once on an empty array. Run it, then make each change below and run it again. Press Reset before each change, so that each one starts from the original program.
• Add a fourth number to the array in numbers.
• Change let product = 1; to let product = 0;.
• Change product = product * n; to product = product + n;, and compare the first line with 3 + 4 + 7. It comes out one more, because the starting value of 1 is added in too.
function productOf(list) {
  let product = 1;
  for (const n of list) {
    product = product * n;
  }
  return product;
}

const numbers = [3, 4, 7];
console.log("Product: " + productOf(numbers));
console.log("Product of an empty array: " + productOf([]));
Output
Press Run to see what this program prints.

Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.