Learn the basics of while loops in JavaScript.
Loops are one of the fundamental constructs that enable us to control the flow of our program. A while loop is a type of loop that repeats a block of code while a specific condition is true. While loops are perfect for when we want to repeat code an unknown number of times.
We actually use while loops in our everyday lives all the time:
In these examples, we’re not quite sure when the road will curve or when exactly the temperature is going to change. So, we continue driving straight until the road curves, or we keep the heat on until the temperature is higher than 68 degrees.
A while loop in JavaScript looks like this:
If the boolean expression evaluates to true
, the code inside the loop will execute. Once the boolean expression evaluates to false
, the computer will exit the while loop and continue on with the program. Click through the slides to walk through a while loop in action.
Look at the example program below. In plain English, it says while there are more than 0 tacos, eat a taco. Run the program and explore with these guiding questions:
numTacos
?numTacos < 0
?Take a look at the While Loops Guessing Game below. Before running the program, predict what you think will happen. What is the while loop condition in plain English? When will the while loop end? (If you are unfamiliar with the !=
symbol, check out the Booleans and Logical Operators tutorial.
When writing a while loop, beware of the infinite loop! An infinite loop occurs when the condition is always true. When there is an infinite loop, the computer will attempt to run the while loop forever, which will ultimately result in crashing the browser or an error.
Let’s revise our tacos program slightly. Look closely - can you figure out why this program would result in an infinite loop?
A hint that you might have an infinite loop on your hands is if you don’t change the value of the variable in the condition. In the above program, we never change the value of numTacos
in our loop. This means that numTacos
will always be 5, which also means that the condition numTacos > 0
will always be true. When the computer runs the program, it will end up repeating the loop an infinite number of times because the condition always evaluates to true
and there is no way to exit the loop.
Which of the following would result in an infinite loop?
You are hosting a small dinner party and have made your famous chili. You’ve calculated that you have 15 scoops of chili and that each person will want between 1-4 scoops, depending on how hungry they are.
Write a program that keeps track of the number of chili scoops left as you serve your guests. Until there are no scoops left, ask a guest for the number of scoops they would like (You can use the readInt("prompt")
command for this). After you serve each guest, update the number of chili scoops. When there are no scoops left, print out a statement informing your guests that there is no more chili left.