AI Hints
JavaScript · Lesson 45 of 138

Looping Arrays

For...of.

⏱ 2 min read▶ Video at 54:30🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Looping Arrays
From the video: Looping Arrays
  • 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.

app.jsjavascript
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}`);
}
Output
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.

keyvalue
for...ofeach item
entries()index and item
Classic forcustom steps
Coming soonmap, 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.

app.jsjavascript
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);
}
Output
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
Next up: Finding Things — indexOf, includes, find