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.

Example 1Try it yourself
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():

Example 2Try it yourself
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:

Example 3Try it yourself
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?

  1. for...in
  2. for...of
  3. for...each
  4. foreach...as
Show answer

Answer: for...of