Introduction to 'While' Loops in JS
While we're at it

Great work with for loops! As a reminder, for loop syntax looks like this:

for (var i = start; i < end; i++) {
  // do something

The counter variable i starts at "start", and stops looping when it reaches "end."

But what if you didn't know ahead of time when to stop looping? Say, for example, you wanted to keep choosing playing cards from a deck until you get a spade. You don't know how many cards you'll need to choose, so a for loop won't work.

In situations like these where you don't know in advance when to stop looping, we can use a while loop.


Check out the while loop in the editor. Can you guess what it will do? Hit "Save & Submit Code" when you think you know! (The answer is in the Hint.)

Don't worry about the Math.floor bit for now—we'll explain it soon!

Stuck? Get a hint! Hint
Get live, fast support from Codecademy Advisors when you get stuck. Learn more.

The code in the editor keeps flipping a coin until it is tails. Here's how it works:

  1. In line 1, we create a variable named coinFace, which is a random number that is either 0 (heads) or 1 (tails).
  2. Then in lines 3-5 we keep flipping the coin as long as the coin turns up heads. If coinFace is 0 (heads), then the condition in the while loop will evaluate to true, and we flip the coin again.
  3. If coinFace is 1 (tails), then the condition will be false, so we break out of the while loop and print Tails! Done flipping.