LoopsExtra· 30 min read

Looping Over Arrays

The most common real use of loops: going through every item in a list.

What you will learn

  • Loop an array with for...of
  • Use forEach
  • Build output from a list

for...of — the easy way

To visit every item in an array, for...of is the cleanest classic loop.

for...of visits each item
<script>
  const fruits = ["Apple", "Mango", "Banana"];
  for (const fruit of fruits) {
    document.write(fruit + "<br>");
  }
</script>
Live preview

Read for (const fruit of fruits) as "for each fruit in the fruits list". On the first turn fruit is "Apple", next "Mango", then "Banana" — the loop hands you one item at a time and runs the body for each.

Note: Output: Apple Mango Banana

forEach — a built-in helper

forEach does the same visiting, but it also hands you the position number (the index) of each item. We build up a string and print it all at once.

forEach gives you the item and its index
<script>
  const scores = [90, 75, 60];
  let html = "";
  scores.forEach(function(score, index) {
    html += "Student " + (index + 1) + ": " + score + "<br>";
  });
  document.write(html);
</script>
Live preview

For every item, forEach calls our function with the value (score) and its index (0, 1, 2...). We write index + 1 so the count reads 1, 2, 3 (friendlier than 0, 1, 2) and add each line onto html. After the loop we print the whole built-up string.

Note: Output: Student 1: 90 Student 2: 75 Student 3: 60

Note: There is also for...in for object keys, and the classic for (let i...) when you need the index. For arrays, for...of and forEach are usually the clearest.

Q. Which loop is cleanest for visiting every value in an array?

Answer: for...of iterates directly over the values of an array — the most readable choice for that job.

✍️ Practice

  1. Loop an array of your friends’ names and print a greeting for each.
  2. Use forEach to print each item with its position number.

🏠 Homework

  1. Given an array of prices, loop to calculate and print the grand total.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →