JavaScript for…of Loop – Iterate Over Collections
The for...of loop in JavaScript provides a simple and convenient way to iterate over iterable objects such as arrays, strings, maps, sets, and more. It retrieves the values of the elements directly without needing to access the index.
1. Syntax of for...of Loop:
for (element of iterable) {
// Code to execute for each element
}
Explanation:
- element: The variable that holds the value of the current element in the iteration.
- iterable: The collection or object being iterated over, such as an array or string.
2. Example of for...of Loop with Arrays:
let fruits = ["Apple", "Banana", "Cherry"];
for (let fruit of fruits) {
console.log(fruit);
}
Output:
Apple Banana Cherry
3. for...of Loop with Strings:
let word = "Hello";
for (let char of word) {
console.log(char);
}
Output:
H e l l o
Explanation:
- The loop iterates over each character in the string.
4. Using for...of with Maps:
let map = new Map();
map.set("name", "John");
map.set("age", 30);
for (let [key, value] of map) {
console.log(`${key}: ${value}`);
}
Output:
name: John age: 30
Explanation:
for...ofiterates over the entries of theMapobject, retrieving both keys and values.
5. Using for...of with Sets:
let set = new Set(["Apple", "Banana", "Cherry"]);
for (let item of set) {
console.log(item);
}
Output:
Apple Banana Cherry
Explanation:
for...ofiterates over the unique elements of aSet.
6. Comparing for...of with forEach:
for...ofworks on all iterable objects and is generally preferred when you need to iterate over the values of an array or collection directly.forEachis specifically for arrays and allows for more control over the execution of functions for each element.
7. for...of with break and continue:
Unlike forEach, you can use break and continue with for...of.
Using break:
let fruits = ["Apple", "Banana", "Cherry"];
for (let fruit of fruits) {
if (fruit === "Banana") {
break;
}
console.log(fruit);
}
Output:
Apple
Using continue:
for (let fruit of fruits) {
if (fruit === "Banana") {
continue;
}
console.log(fruit);
}
Output:
Apple Cherry
Conclusion:
- The
for...ofloop is a powerful and easy-to-use construct for iterating over iterable objects. - It simplifies accessing values directly, making code cleaner and more readable.
- The ability to use
breakandcontinuemakes it more flexible compared toforEach.