JavaScript provides many ways to loop through arrays and other iterable objects. One of these methods is the for...of
loop, which provides an easy and concise way to iterate over the elements of an array.
Syntax
The for...of
loop has the following syntax:
for (variable of iterable) {
// code block to be executed
}
variable
: Required. A new variable to hold each element of the iterable.iterable
: Required. An iterable object, such as an array, a string, or aSet
.
Examples
Let’s take a look at some examples to see how the for...of
loop works:
const numbers = [1, 2, 3, 4, 5];
for (const number of numbers) {
console.log(number);
}
In this example, we define an array of numbers and use the for...of
loop to iterate over each element of the array. The loop creates a new variable number
for each element, which we then log to the console.
const greeting = "Hello, world!";
for (const char of greeting) {
console.log(char);
}
In this example, we define a string greeting
and use the for...of
loop to iterate over each character in the string. The loop creates a new variable char
for each character, which we then log to the console.
const set = new Set([1, 2, 3, 4, 5]);
for (const element of set) {
console.log(element);
}
In this example, we define a Set
object and use the for...of
loop to iterate over each element in the set. The loop creates a new variable element
for each element, which we then log to the console.
Limitations
One thing to note about the for...of
loop is that it only works with iterable objects. It cannot be used with objects or other non-iterable data types.
Another limitation is that it does not provide access to the index of each element, which can be useful in some situations. In these cases, it may be better to use a traditional for
loop.
Conclusion
The for...of
loop provides an easy and concise way to iterate over the elements of an array or other iterable object in JavaScript. While it has some limitations, it can be a useful tool in many situations.