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) {
console.log(list[i])
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 |
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!