Chapter 18

Using While Loops

The while loop will continue to perform its loop as long as its conditions are met. The while loop will do the job until it’s done — no questions asked!

In this chapter, we use a while loop to write a game that will keep buying you sandwiches until you run out of money. The object of the game is to make your lunch money last all week.

image

Writing a while Loop

Compared to for loops, while loops are pretty simple. They only have one part — a Boolean expression — that determines whether the loop will run and continue to run.

Here’s an example of a while loop:

while (money > 0) {

  buyThings();

  saveMoney();

  payTaxes();

}

This loop executes the three functions — buyThings(), saveMoney(), and payTaxes() — as long as the value of the money variable is greater than 0.

The for loop has a final expression that changes the value of the counter. The while loop requires you to have an expression or expressions inside the loop that can change the result of its condition.

The three function calls we created inside the while loop are just made up names. If we were to actually write these functions, they would need to update the value of the money variable so that the loop stops at some point (but, of course, this is one loop we hope doesn’t stop!).

If you don’t modify the value of the variable in a while loop’s condition, you may create what’s called an infinite ...

Get JavaScript For Kids For Dummies now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.