Skip to main content

JavaScript For Of Loop

The for...of loop is a new loop in JavaScript that was introduced in ES6.

It's similar to the for...in loop, but it has some advantages over it.

For example, it can be used to iterate over the elements of an array or a string.

It can also be used to iterate over the properties of an object.

In this tutorial, you'll learn how to use the for...of loop to iterate over the elements of an array or a string.

The basic syntax of a for...of loop:

for (variable of iterable) {
// code to be executed
}

Explanation:

  • variable: This is a variable that will be assigned the value of each element in the iterable object.
  • iterable: This is an iterable object that you want to iterate over.

Here's an example of a for...of loop that prints the elements of an array to the page:

Editor

Loading...

In this example:

  • HTML code creates an unordered list (<ul>) with an ID of numbersList. - Then uses a for...of loop to iterate over the elements of the numbers array.
  • For each number, it logs the value to the console using console.log, and also creates a list item (<li>) and sets its text content to the number using innerText.
  • Finally, the list item is added to the ul element using appendChild.

Looping over a String

In JavaScript, you can loop over a string using a for...of loop or a regular for loop.

Example:

Using a for...of loop:

Editor

Loading...

In this example:

  • HTML code creates an unordered list (<ul>) with an ID of charList.
  • Then uses a for...of loop to iterate over the characters of the myString variable.
  • For each character, it logs the value to the console using console.log, and also creates a list item (<li>) and sets its text content to the character using innerText.
  • Finally, the list item is added to the ul element using appendChild.

Using a regular for loop:

Editor

Loading...

In this example:

  • HTML code creates an unordered list (<ul>) with an ID of charList.
  • Then uses a for loop to iterate over the characters of the myString variable.
  • For each character, it logs the value to the console using console.log, and also creates a list item (<li>) and sets its text content to the character using innerText.
  • Finally, the list item is added to the ul element using appendChild.