Menu
Coddy logo textTech

for...of Loop

Part of the Fundamentals section of Coddy's JavaScript journey — lesson 65 of 77.

The for...of loop provides a simple way to iterate over the values of iterable objects, such as arrays, strings, maps, sets, and more. It combines the conciseness of forEach with the ability to break and continue.

Here's the basic syntax of a for...of loop:

for (const element of iterable) {
    // Code to be executed for each element
}
  • element: On each iteration, the next value from the iterable object is assigned to this variable.
  • iterable: The object whose elements are being iterated over (e.g., an array or a string).

Here's an example with an array:

const fruits = ["apple", "banana", "orange"];

for (const fruit of fruits) {
    console.log(fruit);
}

Output:

apple
banana
orange

Here's another example with a string:

const text = "hello";

for (const char of text) {
    console.log(char);
}

Output:

h
e
l
l
o

Compared to traditional for loops or the forEach method, for...of offers a more straightforward syntax for many common use cases, especially when you don't need the index of each element.

challenge icon

Challenge

Easy

Write a function named countVowels that takes a string as an argument and returns the number of vowels (a, e, i, o, u) in the string. Use a for...of loop to iterate over the characters of the string.

For example:

  • countVowels("hello") should return 2
  • countVowels("javascript") should return 3

Count also upper letters!

Cheat sheet

The for...of loop provides a simple way to iterate over the values of iterable objects like arrays and strings. It combines the conciseness of forEach with the ability to break and continue.

Basic syntax:

for (const element of iterable) {
    // Code to be executed for each element
}

Example with an array:

const fruits = ["apple", "banana", "orange"];

for (const fruit of fruits) {
    console.log(fruit);
}

Example with a string:

const text = "hello";

for (const char of text) {
    console.log(char);
}

Try it yourself

function countVowels(str) {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals