The for...of
loop in JavaScript is a modern loop introduced in ES6 (ECMAScript 2015) that creates a loop iterating over iterable objects. These include arrays, strings, maps, sets, and more, allowing you to directly access the value of each element in the collection. Unlike the for...in
loop, which iterates over the keys or property names of an object, for...of
focuses on the values of iterable objects, making it particularly useful for collections where the order of elements is important.
Syntax
The syntax of the for...of
loop is:
for (variable of iterable) {
// code block to be executed
}
- variable: On each iteration, the value of the next property is assigned to this variable.
- iterable: An object that has iterable properties.
Example Usage
Array
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
This loop logs each fruit in the array to the console.
String
const greeting = "Hello";
for (const char of greeting) {
console.log(char);
}
This example iterates over each character in the string greeting
and logs it to the console.
Map
const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');
for (const [key, value] of map) {
console.log(`${key}: ${value}`);
}
Maps are iterable over their entries, so this loop logs each key-value pair to the console.
Set
const set = new Set([1, 2, 3]);
for (const value of set) {
console.log(value);
}
Since sets are collections of unique values, this loop iterates over each number in the set.
Key Points
- The
for...of
loop provides a cleaner and more concise syntax for iterating over iterable objects compared to traditionalfor
loops. - It avoids all the pitfalls of using
for...in
loops over arrays, such as iterating over inherited properties and non-element properties. - The
for...of
loop cannot directly iterate over plain objects since they are not iterable. To iterate over the properties of an object, you can useObject.keys()
,Object.values()
, orObject.entries()
in combination withfor...of
.
Usage
- The
for...of
loop is a powerful tool for iterating over data structures that are inherently ordered, like arrays or strings. It simplifies the syntax needed to access each element and ensures that the order of elements is respected. - For scenarios where you need to iterate over the properties of an object or require access to the index of an array within the loop, other methods like
for...in
,Object.keys()
, or traditionalfor
loops might be more appropriate.