Modern Iteration Protocols
As JavaScript evolved with ES6, iterating cleanly over Objects and Arrays became much easier with for...of and for...in.
for...of Loop (Arrays / Iterables)
Creates a loop iterating over highly structured iterable objects, primarily Arrays and Strings. It extracts the value directly.
const fruits = ["Apple", "Banana", "Cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
// Apple
// Banana
// Cherry
// It also works beautifully on strings!
const word = "Hello";
for (const char of word) {
console.log(char); // H, e, l, l, o
}
for...in Loop (Objects)
Iterates over all enumerable string properties (keys) of an Object. Since Objects are not strictly iterable sequences like arrays, you cannot use for...of on them.
const user = {
name: "Alice",
age: 28,
role: "Developer"
};
for (const key in user) {
console.log(`Key: ${key}, Value: ${user[key]}`);
}
// Key: name, Value: Alice
// Key: age, Value: 28
// Key: role, Value: Developer
Warning: Avoid using
for...inwith standard Arrays, as it iterates over index strings ("0","1") and any attached properties, which can lead to unexpected behaviors. Stick tofor...offor arrays!