Summary
In this lesson, you learned that:
- A loop repeats a block of code. Each run of the block is an iteration.
while (condition) { ... }repeats the block while the condition is true. Something in the loop must change so that the condition becomes false at some point. Otherwise, the loop never ends, and in these exercises, the program is stopped after 5 seconds.i++andi--add or subtract 1,total += priceadds to a variable andtotal -= pricesubtracts from it.for (let i = 0; i < 5; i++) { ... }has the start, the condition and the step on one line. The counter must be alet, because the step changes it.- A classic
forgoes through the indexes of an array withi < list.length(not<=). for (const item of list) { ... }goes through the elements of an array, or the characters of a text, one by one.- Typical patterns: the sum (a variable that starts at 0 before the loop and adds each value with
+=), the average (the sum divided by.length), counting (count++inside anif) and the largest value (start with the first element and keep every larger one). breakends the whole loop, for example when you have found what you were looking for.continueskips the rest of the current iteration and goes on to the next one.- Loops can be nested: the inner loop runs all the way through in every iteration of the outer one.
Next comes another small project: a game of hangman. Then, in the lesson on functions, you will learn to give a piece of code a name and run it whenever you need it, for example a function that adds up any array of numbers.
Instructions
Let's practice with FizzBuzz, a counting game and a classic programming exercise. The players count from 1, but instead of a number divisible by 3, they say Fizz. With a for loop, print the numbers from 1 to 15, but print Fizz instead of each number divisible by 3 (that is, when i % 3 === 0). The output starts with 1, 2, Fizz, 4.
Now add the full rules: print Buzz instead of numbers divisible by 5, and FizzBuzz instead of numbers divisible by both 3 and 5 (here, that is only 15). Watch the order of your conditions: 15 is also divisible by 3.