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...of
iterates over the entries of theMap
object, 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...of
iterates over the unique elements of aSet
.
6. Comparing for...of
with forEach
:
for...of
works on all iterable objects and is generally preferred when you need to iterate over the values of an array or collection directly.forEach
is 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...of
loop 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
break
andcontinue
makes it more flexible compared toforEach
.