While, Do-While, and For Loops in Javascript

If and else statements let us choose different things to do based on our inputs. Those inputs could come from users or from some other source, like a file or a HTTP request to a server. Being able to choose different courses of action based on inputs is called conditional logic.

While if and else statements let us choose between different branches, they don't let us reuse the same code multiple times. For this we need a loop.

Loops let us repeat doing something until some condition is met (like an if statement). They come in 3 flavors: while, do-while, and for loops.

Note that the while loop is the only one of these which is strictly needed, and in fact some languages, like Rust, only have while loops.

The While Loop

The while loop is the simplest kind of loop. It just repeats until some condition becomes false.

// simple counting while loop
let i = 0;
console.log("Enter loop.")
while (i < 10) {
    console.log(i)
    i++
}
console.log("Exit loop.")

One common use of a while loop is to check if something is true before we execute it:

let i = 0;
max = Number(prompt("> "))
while (i < max) {
  console.log(i)
  i++
}
console.log("Finished")

Exercises

  1. Write a while loop which counts down from a number which the user inputs and stops at 0.
  2. Write a while loop which counts up to a number which the user inputs in steps of 2.
  3. Write a program which asks for numbers over and over again, then returns the total and average of those numbers after the user writes quit.

The Do-While Loop

A do while loop has the same logic as a while loop but it will always execute at least once.

Many developers don't use or rarely use do while loops. This is because in practice, the do-while loop has fairly limited uses, usually to do with taking some sort of input.

let input;
do {
    input = prompt("Enter something you want me to say, or q to exit.")
    console.log(input)
} while (input != "q")

Problems

  1. Write a menu system. When the player enters 1, the system will give them a random number using Math.random(). When the player enters 2, the system will print out the current date and time using console.log(new Date()). When the player enters 3 the program will exit. This will repeat until the player exits the program.

The For Loop

A for loop is a little different to other types of loops. It always creates a new variable (often called an iterator and called i or it) and uses this to go through some set of elements.

It's helpful when you want to do something a certain number of times.

You might also see forEach; this is a different way to do the same thing over a list of items. We'll cover exactly how forEach works in a later part on higher-order functions.

// for loop example

for (let i = 0; i < 10; i++) {
    console.log(i);
}

//////////////////
// foreach example
let list = ['a','b','c','d','e']

// here el means "element"
list.forEach(el => {
    console.log(el)
})

Problems

  1. The formula for compound interest after 1 year is principal * (1 + rate), where principal is the original money invested in USD and rate is a percentage represented as a decimal (i.e. 10% is 0.1). Write a program which calculates the amount some investment is worth after x years. The user should be able to enter the principal, the rate and the number of years to calculate, and the program will print out the interest rate each year up to the number given by the user.
  2. Write a for loop where the user can specify the start value, the end value, and the step size of the loop. For example, if they enter 3, 5, and 1, the program should output:
3
4

If they enter 100, 0, -1, the program should output:

100
99
98
97
...

Loop Keywords

There are two keywords that are helpful to know when writing loops:

  • continue immediately ends this loop and goes onto the next iteration.
  • break ends the entire while or for loop
// continue example
for (let i = 0; i < 10; i++) {
    // skip even numbers
if (i % 2 == 0) {
    continue
} 
console.log(i)
}
// break example
// while true loops forever unless stopped
let i = 0;
while (true) {
    if (i >= 10) break;
    console.log(i);
    i++;
}

Problems

  1. Rewrite your menu system above to use a while(true) loop and keywords.
  2. My friend was born on February 29th, but I can't remember which year. I want a program which counts the number of birthdays she's had since a given year. Write a program which will take a year as an input and log all the years in which my friend celebrated her birthday since that year, then finally log the number of birthdays she celebrated. To avoid working with dates, assume today is January 1st. An example output:
> 1988
1988
1992
1996
2000
2004
2008
2012
2016
2020
Number of birthdays: 9

(Optional) To get more practice in this exercise, you may use while(true) loops and keywords only.

Assignment 1

Let's improve our calculator app from last time. These are two different requirements and you should work on them in this order.

  1. After users have chosen which operation they want to perform, ask them if they want to reset the total to zero or exit the program by taking input. If they decide to reset the total, they should be able to choose an operation to perform again.
  2. Give the user an option to continue working with the same total after adding the two numbers.

Assignment 2

Make a simple game of rock-paper-scissors. The game should work as follows:

  • The player is prompted for a choice of rock-paper-scissors.
  • The computer logs their choice.
  • The winner is declared and logged out.
  • The game prints out how many points the player and the computer have.
  • The game gives players a choice whether to continue with the game or quit.

Remember to set up prompt:

npm install prompt-sync
const prompt = require('prompt-sync')();

You will also want to use Math.random() for the computers' choice of rock, paper, or scissors. You can either look this up or you can copy-paste this snippet:

function getRandomInt(max) {
  return Math.floor(Math.random() * max)
}