DEV Community

Nelson Chibukasia
Nelson Chibukasia

Posted on

for...of Loop in JavaSript

You may have probably encountered different types of loops in JavaScript while learning to code or writing lines of codes to perform an action based on an iteration. There are two major type of loops in JavaScript that are used in iteration, the for loop and the while loop. You might be thinking of do...while loop as a separate loop but for now I'll classify it under the while loop. There are a variety of for loops based on the data type we are looping through or iterating over. These varieties are, the ordinary for loop, for...of to iterate over an array or a collection of html nodes, and for...in to iterate over objects. In this post, We shall focus on the for...of looping technique to iterate over arrays in JavaScripst.

for...of
At this point you may have interacted with different data types in JavaScript such as strings, float, objects, arrays...etc. In this part, we shall only focus on arrays. Well, you might be familiar with arrays at this moment. Arrays are a collection of items packed together. These items can be numbers, strings, nested arrays, boolean, or even the objects. We shall use the for...of to iterate through an array of strings and numbers. The for...of loop is not in any way complicated, in fact, it is pretty straight forward. The for...of uses the format of for (let item of items){code to execute}. Let's put this into practice by looping through an array of numbers and strings.

//create a variable using const to store the array of numbers
const numbers = [24, 67, 84, 38, 39, 92,37];

//loop through the numbers to check it is an even or odd number

for (let number of numbers) {
//code to execute
//checks if number is even or odd
    if (number%2===0){
        console.log(`${number} is even`)
    }else {
        console.log(`${number} is odd`)
    }
}
/*
24 is even
67 is odd
84 is even
38 is even
39 is odd
92 is even
37 is odd
*/
Enter fullscreen mode Exit fullscreen mode

For...of loop can as well be used to loop through an array containing items of any data type. Let's use the for...of loop to loop through an array of strings. We shall capitalize each word in the array.

//create a variable using const to store the array of countries
const countries = ["Kenya", "Sudan", "Nigeria", "Tanzania", "Brazil", "Germany", "India"];

//loop through the countries and convert each country name to uppercase

for (let country of countries) {
    console.log(country.toUpperCase())
}
/*
KENYA
SUDAN
NIGERIA
TANZANIA
BRAZIL
GERMANY
INDIA
*/
Enter fullscreen mode Exit fullscreen mode

Up to this you have learned how to loops through an array using the for...of loop. The **for...of **loop can be used to loop through a collections of html nodes. That's it for this post. Hope you enjoyed reading and happy coding

Top comments (0)