The for...of
loop is a very simple kind of loop.
With this loop you don’t have to worry about the index.
Here’s how use it with the example we’ve been using with the other loops:
const list = ['a', 'b', 'c']
for (const item of list) {
console.log(item)
}
It’s much simpler, right?
One downside is that we don’t have a way to get the index value, which is often useful.
In this case we use a “trick” by combining the array destructuring syntax and calling the entries()
method on the array, which we’ll talk more about later on when we’ll get to iterators:
for (const [index, value] of ['a', 'b', 'c'].entries()) {
console.log(index)
console.log(value)
}
Notice the use of const
when we define item
. This loop creates a new scope in every iteration, so we can safely use that instead of let
. This is not something we can do for the for
loop, where we have to use let
.
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 |