Loops: The `while` loop

The while loop is similar to do..while, but there’s a key difference: with while we first check the condition and then (maybe) we do something.

With do..while, if you remember, first we did something and then we checked if we wanted to do it again.

So it’s a similar loop, but for a different use case.

Here’s an example:

const list = ['a', 'b', 'c']

let i = 0

while (i < list.length) {
  i = i + 1

Same as do..while we have to define and increment i manually to avoid an infinite loop.

You can interrupt a while loop using break:

while (true) {
  if (something) break

and you can jump to the next iteration using continue:

while (true) {
  if (something) continue

  //do something else

Lessons in this unit:

0: Introduction
1: The `for` loop
2: The `do-while` loop
3: ▶︎ The `while` loop
4: The `for-of` loop
5: The `for-in` loop
6: Other kinds of loops
Want to learn more? Check out our courses