JavaScript For-of Loop: A Simplified Guide

Posted by

For-of Loop JavaScript

The For-of Loop in JavaScript

The for-of loop is a new feature introduced in ECMAScript 6 that allows you to iterate over the elements of an iterable object, such as an array or a string. It provides a more concise and readable way to loop through the elements compared to the traditional for loop.

Here is an example of using the for-of loop to iterate over an array:

    
        
            const fruits = ['apple', 'banana', 'orange'];
            
            for (const fruit of fruits) {
                console.log(fruit);
            }
        
    
    

In this example, the for-of loop iterates over each element of the ‘fruits’ array and logs the values to the console. The ‘fruit’ variable represents the current element in each iteration.

The for-of loop can also be used to iterate over the characters of a string:

    
        
            const message = 'Hello, world!';
            
            for (const char of message) {
                console.log(char);
            }
        
    
    

Similarly, in this example, the for-of loop iterates over each character of the ‘message’ string and logs them to the console.

The for-of loop is especially useful when working with iterable objects and provides a more elegant way to loop through their elements. It simplifies the syntax and makes the code easier to read and understand.

Overall, the for-of loop is a powerful tool in JavaScript for iterating over elements of iterable objects, such as arrays and strings. It offers a more modern and concise way to loop through elements compared to the traditional for loop.

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@JaySingh-te1xx
1 month ago

👍