O'Reilly logo

JavaScript For Kids For Dummies by Eva Holland, Chris Minnick

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required