The do..while
loop might be less powerful than for
but it’s also simpler to setup.
With this loop we do something, which we define in a block, and then we decide if we want to do it again.
We have to define an index variable outside of it before we can use it, so it’s more verbose than for
.
Here’s the example we saw in the for
lesson, transformed for do..while
:
const list = ['a', 'b', 'c']
let i = 0
do {
console.log(list[i])
i = i + 1
} while (i < list.length)
Notice that we also have to increment i
manually. If you forget to do so, you will create what’s called an infinite loop.
You can interrupt a while
loop using break
:
do {
if (something) break
} while (true)
and you can jump to the next iteration using continue
:
do {
if (something) continue
//do something else
} while (true)
Lessons 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 |