CodeBlanks Logo Icon CodeBlanks

Summary - Array iteration

JavaScript course · Beginner · Lesson 64/133

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 element
  • for...of: gives values in order, supports break
  • indexOf: returns the first equal index, or -1
  • includes: returns true/false
  • findIndex and some: 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

  1. 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.

  2. 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));

All lessons in Beginner