The For…Of Loop in JavaScript: Simple and Effective Iteration

JavaScript Guide

In JavaScript, there are various methods to iterate over arrays and other iterable objects. One of these methods is the For…Of loop. In this article, we will learn how to use the For…Of loop in JavaScript and when it should be preferred.

What Is the For…Of Loop?

The For…Of loop is a construct used to iterate over an array or other iterable objects. This loop visits each element of the array and performs the specified operation for each element. The For…Of loop is not used to access the indices or properties of the array during iteration; it is specifically used to access the elements themselves.

Using the For…Of Loop

The For…Of loop is used as follows:

const colors = ['red', 'green', 'blue'];

for (const color of colors) {
console.log(color);
}

In the code above, we created an array called colors and used the For…Of loop to print each color using console.log().

For…Of with Arrays

The For…Of loop is highly effective when used with arrays, especially when you want to perform an operation on each element of the array.

const numbers = [1, 2, 3, 4, 5];
let sum = 0;

for (const number of numbers) {
sum += number;
}

console.log('Sum:', sum);

In the code above, we created an array called numbers and summed all its elements. The For…Of loop iterates over each element of the array and adds them to the sum variable.

For…Of with Strings

The For…Of loop can also be used with strings. When you want to iterate over a string, you can use the For…Of loop to access each character.

const str = 'Hello';

for (const char of str) {
console.log(char);
}

In the code above, we created a string called str and printed each character to the console.

For…Of with Other Iterable Objects Like Map, Set, and NodeList

The For…Of loop is not limited to arrays; it can also be used with other iterable objects such as Map, Set, and NodeList. You can use the For…Of loop to visit each element of these objects.

const set = new Set([1, 2, 3]);

for (const item of set) {
console.log(item);
}

In the code above, we created a Set and printed each of its elements to the console.

Conclusion

The For…Of loop provides a simple and effective way to iterate over iterable objects in JavaScript. It can be used with arrays, strings, Map, Set, and other iterable objects. While the For…Of loop is used to access the elements of an array, the For…In loop is preferred when you need to access the indices of an array.

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir