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.
<script>
const fruits = ["Apple", "Mango", "Banana"];
for (const fruit of fruits) {
document.write(fruit + "<br>");
}
</script>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.
<script>
const scores = [90, 75, 60];
let html = "";
scores.forEach(function(score, index) {
html += "Student " + (index + 1) + ": " + score + "<br>";
});
document.write(html);
</script>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?
✍️ Practice
- Loop an array of your friends’ names and print a greeting for each.
- Use
forEachto print each item with its position number.
🏠 Homework
- Given an array of prices, loop to calculate and print the grand total.