JavaScript for of statement | Example code

JavaScript for…of iterates over the values of an iterable object. Examples of iterable objects are arrays, strings, and NodeLists.

Syntax

for (variable of iterable) {
   // statements 
}

Example of JavaScript for of

Let’s take a look at some HTML examples of using the for…of loop.

Iterating over arrays

Easy Loop through the values of an array using for…of:-

<!DOCTYPE html>
<html>
<head>

    <script> 
        var card = ['ABC', 'PQR', 'XYZ'];
        var x;

        for (x of card) {
          document.write(x + "<br >");
      } 
  </script> 

</head>
<body>

</body>
</html>

Output:

JavaScript for of statement array

Iterating over strings

The following example uses the for...of loop to iterate over characters of a string.

<!DOCTYPE html>
<html>
<head>

    <script> 
        var card = 'ABC';
        var x;

        for (x of card) {
          document.write(x + "<br >");
      } 
  </script> 

</head>
<body>

</body>
</html>

Output:

JavaScript for of statement strings

Do comment if you have any suggestions or doubts on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.