When You Don’t Know When to Stop

The while loop is particularly useful when you don’t know how many times the loop needs to execute. Suppose that you are programming a robot whose job is to clean up the toys in your toddler’s room (as a parent, I can attest that such a robot would be really useful). The robot’s job is to keep picking up toys until there are no more toys to pick up. But your toddler might walk into the room while the robot is cleaning and get out some more toys. A while loop is perfect for this situation. Your robot’s code could look something like Listing 7.25.

Listing 7.25 The Robot Keeps Picking up Toys Until There Are No More Toys to Pick Up

var thereAreToysOnTheGround = inspectRoomForToysOnTheGround(); ...

Get Learning to Program 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.