The for...of
loop in JavaScript is used to iterate over iterable objects like arrays, strings, maps, sets, and more. It provides a concise and readable way to access the values of an iterable object directly.
Syntax of for...of
for (variable of iterable) {
// Code to execute for each value
}
variable
: A variable that stores the current value of the iteration.iterable
: An object that is iterable (e.g., Array, String, Map, Set).
Features of for...of
Iterates Over Values
Thefor...of
loop retrieves the values of the iterable instead of the keys or indices.Works with Iterables
It works seamlessly with iterable objects like arrays, strings, maps, sets, and more.Readable Syntax
for...of
is simpler and more readable than traditional loops for iterating over values.
Examples
1. Iterating Over an Array
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
// Outputs:
// apple
// banana
// cherry
2. Iterating Over a String
const word = "hello";
for (const letter of word) {
console.log(letter);
}
// Outputs:
// h
// e
// l
// l
// o
3. Iterating Over a Set
const uniqueNumbers = new Set([1, 2, 3, 4]);
for (const num of uniqueNumbers) {
console.log(num);
}
// Outputs:
// 1
// 2
// 3
// 4
4. Iterating Over a Map
const userRoles = new Map([
["Junaid", "Admin"],
["Arsheen", "Editor"],
["Kinza", "Viewer"]
]);
for (const [user, role] of userRoles) {
console.log(`${user}: ${role}`);
}
// Outputs:
// Junaid: Admin
// Arsheen: Editor
// Kinza: Viewer
Comparison: for...of
vs for...in
Feature | for...of | for...in |
---|---|---|
Iterates Over | Values of the iterable | Keys or indices |
Works On | Arrays, Strings, Maps, Sets, etc. | Objects, Arrays |
Use Case | Accessing values | Accessing keys or properties |
Best Practices
Use for Arrays and Strings
When working with arrays or strings,for...of
is simple and efficient.Avoid for Objects
For plain objects, usefor...in
orObject.keys()
/Object.values()
.Use with Maps and Sets
for...of
is ideal for iterating over key-value pairs in maps and unique elements in sets.
The for...of
loop is a modern and intuitive way to iterate over iterable objects in JavaScript. It simplifies accessing values and enhances code readability. While it’s not suitable for every scenario, it’s a powerful tool when working with arrays, strings, and other iterable structures.