Loops: The `for-of` loop

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
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!