We've learned for
loops are great when we know exactly how many times to repeat something. But what if we want to keep doing something until a certain condition is met?
Engagement Message
Can you think of a situation where you'd repeat an action an unknown number of times?
For example, "keep asking for a password until the correct one is entered" or "keep rolling a dice until you get a 6." We don't know how many attempts this will take!
Engagement Message
How is this different from printing something exactly 5 times?
JavaScript has another type of loop for this called a while
loop. It repeats a block of code as long as a condition remains true
. When the condition becomes false
, the loop stops.
Engagement Message
What do you think happens if the condition never becomes false
?
Here's the basic structure:
Just like if
statements, we use parentheses for the condition and curly braces for the code block.
Engagement Message
What familiar syntax do you see?
