for...of loops over the values of anything iterable: arrays, strings, Maps, Sets and more. It is the cleanest way to visit each item.
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}
No index, no length, no i++. Use const for the loop variable when you do not reassign it.
Works on strings too
for (const letter of "Hi!") {
console.log(letter); // H, i, !
}
It handles Unicode characters better than indexing, because it walks over whole characters, so emoji are not split in two.
Getting the index
Use entries() and destructuring:
const names = ["Maya", "Arjun"];
for (const [index, name] of names.entries()) {
console.log(index, name);
}
Maps and Sets
const prices = new Map([["tea", 3], ["coffee", 4]]);
for (const [item, price] of prices) {
console.log(item, price);
}
for (const value of new Set([1, 2, 2, 3])) {
console.log(value); // 1, 2, 3
}
Objects are not iterable
A plain object cannot be used with for...of directly. Loop over its keys, values or entries instead:
const user = { name: "Maya", age: 25 };
for (const [key, value] of Object.entries(user)) {
console.log(key, value);
}
break and continue work
for (const n of [1, 2, 3, 4, 5]) {
if (n === 4) break;
console.log(n); // 1, 2, 3
}
Make it your default
for...of is usually clearer than a classic for loop. You will see how it works behind the scenes in Iterables and Iterators.