for...of and entries β Modern Iteration Patterns
After this topic
You will understand the differences between for...of, for...in, and forEach, and be able to choose the appropriate iteration method for the situation.
Don't use for...in with arrays
const fruits = ["apple", "banana", "cherry"];
for (const i in fruits) {
console.log(i); // "0", "1", "2" β index as a string
}for...in iterates over the keys of an object. When used with an array, it returns the indices as strings. It can also iterate over properties in the prototype chain, which can lead to unexpected results.
for...of iterates over values
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit); // "apple", "banana", "cherry"
}for...of directly iterates over the values of an iterable. It can be used with arrays, strings, Maps, Sets, and more.
for (const char of "hello") {
console.log(char); // "h", "e", "l", "l", "o"
}Use entries() if you need the index
for...of only gives you the values. If you need the index, use entries():
const fruits = ["apple", "banana", "cherry"];
for (const [index, fruit] of fruits.entries()) {
console.log(`${index}: ${fruit}`);
}
// 0: apple
// 1: banana
// 2: cherryYou can use destructuring to get both the index and the value at the same time. It's similar to Python's enumerate().
forEach vs for...of
// forEach
fruits.forEach((fruit, index) => {
console.log(`${index}: ${fruit}`);
});
// for...of
for (const [index, fruit] of fruits.entries()) {
console.log(`${index}: ${fruit}`);
}Both seem similar, but there is a key difference:
forEach cannot be stopped mid-iteration. break and return do not stop the entire loop (return only exits the current callback).
// for...of β break is possible
for (const fruit of fruits) {
if (fruit === "banana") break;
console.log(fruit); // only outputs "apple"
}
// forEach β break is not possible
fruits.forEach(fruit => {
if (fruit === "banana") return; // only skips this callback
console.log(fruit); // outputs "apple", "cherry"
});If you need to stop mid-iteration, use for...of. If you need to iterate over the entire collection, use forEach or map.
Iterating over objects
You cannot directly iterate over a plain object with for...of. Use Object.entries():
const user = { name: "Alice", age: 25, city: "Seoul" };
for (const [key, value] of Object.entries(user)) {
console.log(`${key}: ${value}`);
}
// name: Alice
// age: 25
// city: SeoulObject.keys() returns only the keys, and Object.values() returns only the values.
Key takeaway
for...initerates over the keys of an object, whilefor...ofiterates over the values of an iterable. If you need the index in an array, useentries(). If you need tobreakmid-iteration,for...ofis suitable. If you need to iterate over the entire collection,forEachis appropriate.