Cityscape
Girl

JavaScript

For...Of Loop - Repeating an Action for Each Item in a List

Easy
15 min

What Is a For...of Loop?

In JavaScript, a for...of loop is used to iterate over the values of an iterable object, like an array.

The basic syntax is:

for (let item of items) {
  // Execute code using item
}
  • item: A variable that represents the current element in the iteration.
  • items: An iterable object (like an array).

How It Works

When the for...of loop is executed, it goes through the iterable one value at a time. For each iteration, the variable (e.g., item) is set to the current element of the iterable, and the loop body executes using that element.

Example: Printing Each Number

Suppose you have an array of numbers. Using a for...of loop, you can print each number without needing to use an index:

let numbers = [1, 2, 3, 4, 5];

for (let num of numbers) {
  console.log(num);
}

Explanation:
This code initializes the array numbers with five values. The for...of loop goes through each number (assigning it to the variable num) and prints it to the console.

Exercises

Print Each Fruit

  • Create a variable called fruits and assign it an array of at least three different fruit names.
  • Use a for…of loop to print each fruit to the console.

hakatemia pro

Ready to become an ethical hacker?
Start today.

As a member of Hakatemia you get unlimited access to Hakatemia modules, exercises and tools, and you get access to the Hakatemia Discord channel where you can ask for help from both instructors and other Hakatemia members.