for...of and for...in
for...of: the values
for...of loops over the values of anything iterable: arrays, strings, Maps, Sets.
JavaScript
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
for (const ch of "Hi!") {
console.log(ch);
}It's the clearest loop for arrays, and it works with break and continue.
Index and value together
JavaScript
const players = ["Asha", "Leo", "Mei"];
for (const [i, name] of players.entries()) {
console.log(`${i + 1}. ${name}`);
}entries() yields [index, value] pairs, which destructuring unpacks.
for...in: the keys
for...in loops over the keys of an object:
JavaScript
const scores = { Asha: 92, Leo: 78, Mei: 85 };
for (const name in scores) {
console.log(name, scores[name]);
}JavaScript
const arr = [10, 20, 30];
for (const i in arr) console.log(i, typeof i);
for (const v of arr) console.log(v, typeof v);Objects with for...of
Objects aren't iterable themselves, but Object.entries() turns one into an array of pairs:
JavaScript
const prices = { tea: 20, coffee: 35, juice: 50 };
for (const [item, price] of Object.entries(prices)) {
console.log(`${item}: ₹${price}`);
}
const total = Object.values(prices).reduce((a, b) => a + b, 0);
console.log("Total:", total);forEach
Arrays also have a forEach method, which calls a function for each item:
JavaScript
["red", "green", "blue"].forEach((colour, i) => {
console.log(i, colour);
});forEach can't be stopped with break; use for...of when you might need to stop early.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.