Mastering the JavaScript For-of Loop: A Comprehensive Guide

Rumman Ansari   Software Engineer   2024-07-28 02:22:57   489  Share
Subject Syllabus DetailsSubject Details 2 Questions
☰ TContent
☰Fullscreen

Table of Content:

JavaScript For-in Loop

JavaScript For-in Loop is used to loop through the items of an iterable object.

In this tutorial, we will learn how to define/write a JavaScript For-of loop, and its usage using example programs.

Syntax

The syntax of JavaScript For-of Loop is


for (item of iterableObj) {
     //statements
 }

where item is loaded with the next item of iterableObj object during each iteration.

for and of are keywords.

Examples

In the following example, we take an array, which is an iterable object, and use For-of loop to iterate over the items of this array.


<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var obj = ['apple', 'banana', 'orange'];
        var output = document.getElementById('output');
        for (item of obj) {
            output.innerHTML += item + '\n';
        }
    </script>
</body>
</html>

Now, let us take a string object, and iterate over the character using For-of loop. String is an iterable object which returns next character during each iteration.


<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var obj = 'apple';
        var output = document.getElementById('output');
        for (item of obj) {
            output.innerHTML += item + '\n';
        }
    </script>
</body>
</html>
MCQ Available

There are 1 MCQs available for this topic.

1 MCQ


Stay Ahead of the Curve! Check out these trending topics and sharpen your skills.