The `for...of` loop is a modern iteration construct in JavaScript that allows you to iterate over iterable objects, such as arrays, strings, maps, sets, and more.
JavaScript for...of Loop
1. Syntax
The syntax of the `for...of` loop is as follows:
for (const element of iterable) {
// Code to execute for each element
}
Here, iterable
is the object you want to iterate over, and element
represents the current value during each iteration.
2. Example: Iterating Over an Array
Here's a basic example of using the `for...of` loop to iterate over an array:
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
console.log(fruit);
}
This will output:
apple
banana
cherry
3. Example: Iterating Over a String
You can also use the `for...of` loop to iterate over a string:
const message = 'Hello';
for (const char of message) {
console.log(char);
}
This will output:
H
e
l
l
o
4. Example: Iterating Over a Set
The `for...of` loop works with sets as well:
const numbers = new Set([1, 2, 3, 4]);
for (const number of numbers) {
console.log(number);
}
This will output:
1
2
3
4
5. Using for...of with Objects
The `for...of` loop cannot be used directly with plain objects. To iterate over the properties of an object, use Object.keys()
, Object.values()
, or Object.entries()
:
const person = { name: 'Alice', age: 25 };
for (const key of Object.keys(person)) {
console.log(key + ': ' + person[key]);
}
This will output:
name: Alice
age: 25
6. Benefits of Using for...of
- Cleaner and more readable syntax compared to traditional
for
loops. - Automatically handles the iteration for you, reducing the chance of errors.
- Works with any iterable object, making it a versatile choice for iteration.
7. Conclusion
The `for...of` loop is a powerful and concise way to iterate over iterable objects in JavaScript. It improves code readability and helps avoid common pitfalls associated with traditional loop constructs.