Lesson 128 – Complete 2020 Web Development Bootcamp

Lesson 128 – Control Statements: While Loops

While loops allow you to run code while a specified condition exists. For example this is a while loop that runs the FizzBuzz function from the previous lesson as long as the variable “count” is less than or equal to 100.

var output = [];
var count = 1;

function fizzBuzz() {

    while (count <= 100) {
    
    if (count % 3 === 0 && count % 5 === 0) {
        output.push("FizzBuzz")
    }

    else if (count % 3 === 0) {
        output.push("Fizz")
    }

    else if (count % 5 === 0) {
        output.push("Buzz")
    }

    else {
        output.push(count);
    }

    count = count + 1;
  }
    console.log(output);

 }

fizzBuzz();

While loops are error prone. In the above example, if you forget to increment the count with the code “count = count +1;”, then the while loop will create an infinite loop which runs infinitely and will cause the code to crash.

The challenge in this lesson is to use a while loop to print out the lyrics in the song “99 Bottles of Beer”.

This is my solution:

var bottles = 99;

function beer() {

while(bottles >= 1) {

    if (bottles >= 2) {

     console.log(bottles + " bottles of beer on the wall. Take one 
     down and pass it around. " + (bottles - 1) + " bottles of beer on 
     the wall.")
      }

    else {

     console.log(bottles + " bottle of beer on the wall. Take one down 
     and pass it around. No more bottles of beer on the wall.")
     }

    bottles = bottles - 1;
     }
   }

beer();