The JavaScript for..of loop
By Flavio Copes
Learn the JavaScript for..of loop, combining the conciseness of forEach with the ability to break and continue, plus getting the index with entries().
The for...of loop is my favorite way to loop in JavaScript.
It combines the conciseness of forEach loops with the ability to break.
Before it existed, you had to choose. A classic for loop can stop early, but you manage the index yourself. forEach() is compact, but there is no way to stop it once it starts. for...of gives you both: clean syntax, plus break and continue when you need them.
The syntax is this:
const list = ['a', 'b', 'c']
for (const item of list) {
console.log(item)
}
Each iteration assigns the next element to item. No index bookkeeping, no list[i].
You can break at any point in time using break:
const list = ['a', 'b', 'c']
for (const item of list) {
console.log(item)
if (item === 'b') break
}
This prints a and b, then stops.
You can skip an iteration using continue:
const list = ['a', 'b', 'c']
for (const item of list) {
if (item === 'b') continue
console.log(item)
}
This prints a and c.
You can get the index of an iteration using entries():
const list = ['a', 'b', 'c']
for (const [index, value] of list.entries()) {
console.log(index) //index
console.log(value) //value
}
entries() produces [index, value] pairs, and the array destructuring in the loop header unpacks each pair into two variables.
Notice the use of const. The for..of loop creates a new scope in every iteration, so we can safely use that instead of let.
It works on any iterable
for...of is not limited to arrays. It loops over any iterable: strings, Map, Set, the NodeList you get from document.querySelectorAll(), and more.
for (const char of 'hey') {
console.log(char) //h, e, y
}
What it cannot loop over is a plain object:
const car = { color: 'green' }
for (const prop of car) {
} //TypeError: car is not iterable
That TypeError: <thing> is not iterable is the failure you will hit most often with this loop. Objects are not iterable. When you need to walk an object, loop over Object.keys(car), Object.values(car), or Object.entries(car) instead — those return arrays, and arrays work.
Related posts about js: