Iterating over collections
Most of the time you don't want to count bare numbers, but to go through the
elements of a list: the products in a cart, the names in a group, the
letters in a word. For that there are versions of for that are far more
convenient, and read almost like a sentence.
for...of: iterates over the values
Ideal for arrays and strings. On each round it gives you the element directly:
const fruits = ["apple", "pear", "grape"];
for (const fruit of fruits) {
console.log(fruit);
}
// "apple", "pear", "grape"
It also works with strings, character by character:
for (const letter of "abc") {
console.log(letter); // "a", "b", "c"
}
for...in: iterates over the keys/indices
Meant for objects, where it gives you the name of each property:
const person = { name: "Ana", age: 25 };
for (const key of person) {} // ❌ this does NOT work
for (const key in person) {
console.log(key, "=>", person[key]);
}
// "name => Ana", "age => 25"
Trick to not get confused:
ofmeans "give me the values" of arrays/strings;inmeans "give me the keys" of objects. If you mix them up, no worries: even veterans second-guess this one sometimes.
Controlling the flow: break and continue
breakexits the loop immediately.continuejumps to the next round, ignoring the rest of the body.
for (let i = 1; i <= 10; i++) {
if (i === 5) break; // when reaching 5, stop entirely
if (i % 2 === 0) continue; // ignore even numbers
console.log(i); // prints 1, 3
}
Examples
Iterate over an array with for...of
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color.toUpperCase());
}
Skip and stop with continue and break
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) continue; // skip even numbers
if (i > 5) break; // when reaching 7, stop entirely
console.log(i); // prints 1, 3, 5
}