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 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 |
Are you intimidated by Git? Can’t figure out
merge vs rebase? Are you afraid of screwing up
something any time you have to do something in
Git? Do you rely on ChatGPT or random people’s
answer on StackOverflow to fix your problems?
Your coworkers are tired of explaining Git to
you all the time? Git is something we all need
to use, but few of us really master it. I
created this course to improve your Git (and
GitHub) knowledge at a radical level. Launching
May 21, 2024. Join the waiting list!