The for…of loop in JavaScript is a convenient way to iterate over iterable objects, such as arrays, strings, sets, maps, and more.
Introduced in ES6 (ECMAScript 2015), for…of provides an elegant syntax to traverse data structures without having to worry about indexing or object properties.
This tutorial will explore the for…of loop with several practical examples.
Table of Contents
1. Basic Syntax of for…of Loop
The syntax of the for…of loop is simple and intuitive:
for (const element of iterable) { // Code to execute for each element }
element: A variable that will hold the value of the current element in each iteration.
iterable: The object you want to loop over (arrays, strings, sets, maps, etc.).
2. Using for…of with Arrays
The for…of loop is commonly used to iterate over elements of an array.
Example 1: Iterating Over an Array
const fruits = ['apple', 'banana', 'orange']; for (const fruit of fruits) { console.log(fruit); }
Output:
apple banana orange
Explanation: The loop iterates over each element in the fruits array, logging each fruit to the console.
3. Using for…of with Strings
The for…of loop can iterate over each character in a string.
Example 2: Iterating Over a String
const message = 'Hello, World!'; for (const char of message) { console.log(char); }
Output:
H e l l o , W o r l d !
Explanation: The loop iterates over each character in the string, including spaces and punctuation.
4. Using for…of with Sets
Sets are collections of unique values. The for…of loop can be used to iterate over elements in a Set.
Example 3: Iterating Over a Set
const uniqueNumbers = new Set([1, 2, 3, 4, 5]); for (const number of uniqueNumbers) { console.log(number); }
Output:
1 2 3 4 5
Explanation: The loop iterates over each element in the Set, logging each number to the console. Duplicate values are not included in the set.
5. Using for…of with Maps
Maps store key-value pairs, and for…of can be used to iterate over a map’s entries, keys, or values.
Example 4: Iterating Over a Map's Entries
const userRoles = new Map([ ['Alice', 'Admin'], ['Bob', 'Editor'], ['Charlie', 'Viewer'] ]); for (const [user, role] of userRoles) { console.log(`${user}: ${role}`); }
Output:
Alice: Admin Bob: Editor Charlie: Viewer
Explanation: The loop iterates over each entry in the map. The destructuring assignment ([user, role]) extracts the key and value from each map entry.
Example 5: Iterating Over a Map's Keys and Values
const userRoles = new Map([ ['Alice', 'Admin'], ['Bob', 'Editor'], ['Charlie', 'Viewer'] ]); // 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 Bob Charlie Admin Editor Viewer
Explanation: You can use userRoles.keys() and userRoles.values() to iterate over the keys and values of the map, respectively.
6. Using for…of with Arrays and entries()
The entries() method returns an iterator object containing key-value pairs for each index in an array. Using for…of with entries() allows you to get both the index and the value in each iteration.
Example 6: Iterating Over Array with Index and Value
const colors = ['red', 'green', 'blue']; for (const [index, color] of colors.entries()) { console.log(`Index: ${index}, Value: ${color}`); }
Output:
Index: 0, Value: red Index: 1, Value: green Index: 2, Value: blue
Explanation: The entries() method returns an iterator containing arrays of index-value pairs, which are then destructured in the for…of loop.
7. Using for…of with NodeLists (DOM Elements)
When working with the DOM, you often need to iterate over collections of elements. NodeList objects (returned by methods like document.querySelectorAll) are iterable and can be traversed using for…of.
Example 7: Iterating Over DOM Elements
// Assuming there are multiple
elements on the page const paragraphs = document.querySelectorAll(‘p'); for (const paragraph of paragraphs) { paragraph.style.color = ‘blue'; // Changes the text color of each
element to blue }
Explanation: The for…of loop iterates over each
element in the NodeList and applies a style change to it.
8. Using for…of with Generators
Generators are a special type of function that can be paused and resumed. They produce a sequence of values, making them iterable.
Example 8: Iterating Over a Generator
function* numberGenerator() { yield 1; yield 2; yield 3; } const numbers = numberGenerator(); for (const number of numbers) { console.log(number); }
Output:
1 2 3
Explanation: The for…of loop iterates over each value produced by the generator function.
9. Difference Between for…of and for…in
for…of: Iterates over the values of an iterable (like arrays, strings, sets, and maps).
for…in: Iterates over the keys (property names) of an object or array indices.
Example 9: for…of vs. for…in
const arr = ['a', 'b', 'c']; console.log('Using for...of:'); for (const value of arr) { console.log(value); // Outputs the values: a, b, c } console.log('Using for...in:'); for (const index in arr) { console.log(index); // Outputs the indices: 0, 1, 2 }
Output:
Using for...of: a b c Using for...in: 0 1 2
Explanation: for…of iterates over the values of the array, while for…in iterates over the indices (keys).
Conclusion
The for…of loop is a versatile tool for iterating over various types of iterable objects in JavaScript, including arrays, strings, sets, maps, NodeList objects, and even generators.
It simplifies the iteration process by allowing you to focus on the elements themselves rather than their indices or properties.
Experiment with these examples to get a solid understanding of how for…of can be used in different scenarios!