Looping Arrays
For...of.
Most of the time, you want to do something with every item in an array. Print each name, or add up each price. JavaScript has a clean loop for exactly that.

- Do something with every item
- Print, add up
- A clean loop
for of
For, const price, of prices, gives us each item in turn, with no index to manage. If you also need the position, entries gives you the index and the item together. Run it.
const prices = [4.5, 12, 7.25];
let total = 0;
for (const price of prices) {
total += price;
}
console.log("Total:", total);
for (const [i, price] of prices.entries()) {
console.log(`Item ${i + 1}: $${price}`);
}Total: 23.75 Item 1: $4.5 Item 2: $12 Item 3: $7.25
Which loop?
Use for of when you just need each item. It's short, and you can't get the index wrong. Use a classic for loop with a counter when you need to jump around, or go backwards. And soon, we'll meet array methods like map and filter, which often replace loops entirely.
| key | value |
|---|---|
| for...of | each item |
| entries() | index and item |
| Classic for | custom steps |
| Coming soon | map, filter, reduce |
forEach and the index
Arrays also have a for each method. It calls a function for every item, and gives you the index as a second argument. Here we number the items from one. And entries, with for of, gives you the index and the item together. Run it.
const songs = ["Intro", "Sunrise", "Finale"];
songs.forEach((song, i) => {
console.log(`${i + 1}. ${song}`);
});
for (const [i, song] of songs.entries()) {
if (i === songs.length - 1) console.log("Last song:", song);
}1. Intro 2. Sunrise 3. Finale Last song: Finale
Summary
For of loops through each item of an array, and entries adds the index. Next, finding things in arrays.
Key takeaways- for (const x of arr)
- arr.entries()
- No index mistakes