Explore the powerful `for...of` loop introduced in ES6, ideal for iterating over iterable objects like arrays and strings. Learn its syntax, usage, and differences from `for...in`.
for...of
Loop (ES6)In this section, we will explore the for...of
loop, a powerful feature introduced in ECMAScript 6 (ES6) that allows us to iterate over iterable objects such as arrays and strings. The for...of
loop provides a more readable and concise syntax for iterating over elements, making it a valuable tool for JavaScript developers.
for...of
LoopThe for...of
loop is designed to iterate over iterable objects. But what exactly is an iterable object? In JavaScript, an iterable is an object that implements the @@iterator
method, which returns an iterator. This iterator is an object that adheres to the iterator protocol, providing a next()
method that returns an object with two properties: value
and done
.
The most common iterable objects in JavaScript are arrays and strings, but other data structures like Maps, Sets, and even the arguments object are also iterable. Let’s start by understanding how the for...of
loop works with arrays and strings.
for...of
LoopThe syntax of the for...of
loop is straightforward and easy to understand:
for (const element of iterable) {
// Code to execute for each element
}
element
: A variable that holds the current element of the iterable object during each iteration.iterable
: An iterable object (e.g., an array or a string) that you want to loop over.Arrays are one of the most common data structures in JavaScript, and the for...of
loop is particularly useful for iterating over them. Let’s see how it works with an example:
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
console.log(fruit);
}
Output:
apple
banana
cherry
Explanation:
fruits
containing three elements: 'apple'
, 'banana'
, and 'cherry'
.for...of
loop iterates over each element of the fruits
array.fruit
, and we log it to the console.Strings are also iterable, which means we can use the for...of
loop to iterate over each character in a string. Here’s an example:
const greeting = 'Hello';
for (const char of greeting) {
console.log(char);
}
Output:
H
e
l
l
o
Explanation:
greeting
with the value 'Hello'
.for...of
loop iterates over each character in the string.char
, and we log it to the console.for...in
and for...of
It’s important to understand the differences between the for...in
and for...of
loops, as they serve different purposes and can lead to different results.
for...in
LoopThe for...in
loop is used to iterate over the enumerable properties of an object. This includes properties that are inherited through the prototype chain, which can sometimes lead to unexpected results when used with arrays.
Example of for...in
with an array:
const fruits = ['apple', 'banana', 'cherry'];
for (const index in fruits) {
console.log(index); // Logs the indices: 0, 1, 2
console.log(fruits[index]); // Logs the elements: apple, banana, cherry
}
Key Points:
for...in
loop iterates over the keys (indices) of the array, not the values.for...of
LoopThe for...of
loop, on the other hand, is specifically designed to iterate over the values of iterable objects, such as arrays and strings.
Example of for...of
with an array:
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
console.log(fruit); // Logs the elements: apple, banana, cherry
}
Key Points:
for...of
loop iterates over the values of the array, not the indices.for...of
The for...of
loop offers several advantages over other iteration methods:
for...in
, the for...of
loop does not iterate over inherited properties, making it safer for array iteration.for...of
with Other IterablesWhile arrays and strings are the most common use cases, the for...of
loop can also be used with other iterable objects such as Maps, Sets, and the arguments object.
A Set is a collection of unique values. Here’s how you can iterate over a Set using the for...of
loop:
const uniqueNumbers = new Set([1, 2, 3, 4, 5]);
for (const number of uniqueNumbers) {
console.log(number);
}
Output:
1
2
3
4
5
A Map is a collection of key-value pairs. You can iterate over the entries, keys, or values of a Map using the for...of
loop:
const userRoles = new Map([
['Alice', 'Admin'],
['Bob', 'Editor'],
['Charlie', 'Viewer']
]);
// Iterating over entries
for (const [user, role] of userRoles) {
console.log(`${user}: ${role}`);
}
// Iterating over keys
for (const user of userRoles.keys()) {
console.log(user);
}
// Iterating over values
for (const role of userRoles.values()) {
console.log(role);
}
Output:
Alice: Admin
Bob: Editor
Charlie: Viewer
Alice
Bob
Charlie
Admin
Editor
Viewer
Now that we’ve covered the basics of the for...of
loop, let’s try some hands-on exercises to reinforce your understanding.
Create an array of your favorite colors and use a for...of
loop to log each color to the console.
Choose a word and use a for...of
loop to log each character of the word to the console.
Create a Map with the names of three countries as keys and their capitals as values. Use a for...of
loop to log each country and its capital to the console.
for...of
LoopTo help visualize how the for...of
loop works, let’s use a flowchart to represent the iteration process:
flowchart TD A[Start] --> B[Initialize Iterable] B --> C[Get Iterator] C --> D{Has Next Element?} D -- Yes --> E[Get Next Element] E --> F[Execute Code Block] F --> D D -- No --> G[End]
Description:
The for...of
loop is a versatile and powerful tool for iterating over iterable objects in JavaScript. It simplifies the process of iterating over arrays, strings, and other iterable data structures, providing a clean and readable syntax. By understanding the differences between for...in
and for...of
, you can choose the right loop for your specific use case and avoid common pitfalls.
For more information on the for...of
loop and iterables in JavaScript, you can explore the following resources: