JavaScript Tutorial · Control Flow · Lesson 17 of 44
JavaScript for...of and for...in
Loop over array values, string characters and object keys.
for...of — values
for...of loops over the values of any iterable: arrays, strings, Maps, Sets.
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
for (const ch of "Hi!") {
console.log(ch);
}
Output
apple banana cherry H i !
Need the index too? Use entries():
const fruits = ["apple", "banana", "cherry"];
for (const [index, fruit] of fruits.entries()) {
console.log(index, fruit);
}
Output
0 apple 1 banana 2 cherry
for...in — keys
for...in loops over the property names of an object. Don't use it for arrays (it gives string indexes and includes inherited properties). For objects, Object.entries() with for...of is usually clearer:
const prices = { coffee: 3, tea: 2.5, cake: 4 };
for (const key in prices) {
console.log(key, prices[key]);
}
for (const [item, price] of Object.entries(prices)) {
console.log(`${item}: $${price.toFixed(2)}`);
}
Output
coffee 3 tea 2.5 cake 4 coffee: $3.00 tea: $2.50 cake: $4.00
Test yourself
Which loop gives you the values of an array?
for...infor...offor...eachforeach...as
Show answer
Answer: for...of