Summary - Array iteration
Print a task list using forEach and for...of.
Summary - Array iteration
In this group you learned several ways to loop over arrays and search them:
forEach: runs a callback for each elementfor...of: gives values in order, supportsbreakindexOf: returns the first equal index, or-1includes: returnstrue/falsefindIndexandsome: predicate queries
Now you will combine them on a task list.
Exercise Print the tasks array with its index
Create an array named tasks with at least three task strings. Use forEach to print each task with its index in the form "1. task" with console.log. Although the index starts at 0, the output should start from 1 (use i + 1).
Show example solution
Give the forEach callback two parameters (task, i), then build the number with i + 1.
Example solution:
const tasks = ["homework", "sport", "sleep"];
tasks.forEach((task, i) => console.log((i + 1) + ". " + task));
Exercise Print the colors array with for...of
Create an array named colors with at least four color strings. Use for...of to print each color with console.log.
Show example solution
Write the array, then traverse each color with for...of and print it with console.log.
Example solution:
const colors = ["red", "blue", "green", "yellow"];
for (const color of colors) {
console.log(color);
}
Test yourself
-
Which is the most suitable to check membership with a true/false answer?
- includes
- indexOf
- for...of
- findIndex
Show answer
includes — Correct. includes returns true/false directly; no extra comparison needed.
-
Print each task with forEach
const tasks = ["homework", "sport", "sleep"]; tasks.forEach(task => console.log(____));Show answer
const tasks = ["homework", "sport", "sleep"]; tasks.forEach(task => console.log(task));