1. Iterating Over an Array using for...of
Arrays are one of the most common data structures in JavaScript, and the for...of loop makes iterating over them simple and straightforward. Unlike the traditional for loop, which requires keeping track of indices, the for...of loop allows you to directly access the values of the array.
Example:
const fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
for (let fruit of fruits) {
console.log(fruit);
}

You can also try this code with Online Javascript Compiler
Run Code
Explanation:
In this example, the for...of loop iterates over each element in the fruits array. On each iteration, the value of the current element is assigned to the variable fruit, which is then logged to the console.
Output:
Apple
Banana
Cherry
Date
This shows how easy it is to loop through an array using the for...of loop without manually managing the array index.
2. Iterating Over a String using for...of
Strings in JavaScript are also iterable objects, meaning you can use the for...of loop to access each character in the string. This is useful when you need to process or manipulate individual characters within a string.
Example:
const word = "JavaScript";
for (let char of word) {
console.log(char);
}

You can also try this code with Online Javascript Compiler
Run Code
Explanation:
Here, the for...of loop goes through each character of the string word. Each character is logged to the console one by one.
Output:
J
a
v
a
S
c
r
i
p
t
This demonstrates how the for...of loop can be used to iterate over a string, making the code cleaner and more readable.
3. Iterating Over a Map using for...of
Maps are another iterable object in JavaScript. A Map is a collection of key-value pairs, and the for...of loop can be used to iterate through each pair. The loop can be used to directly access both the keys and values of the map.
Example:
const studentGrades = new Map([
['Alice', 'A'],
['Bob', 'B'],
['Charlie', 'A'],
['David', 'C']
]);
for (let [student, grade] of studentGrades) {
console.log(`${student}: ${grade}`);
}

You can also try this code with Online Javascript Compiler
Run Code
Explanation:
In this example, the for...of loop iterates over the map studentGrades. On each iteration, both the student (key) and grade (value) are extracted and printed in a formatted manner.
Output:
Alice: A
Bob: B
Charlie: A
David: C
Using for...of with maps simplifies working with key-value pairs, making your code cleaner and more efficient.
4. Iterating Over a Set using for...of
Sets are collections of unique values in JavaScript, and the for...of loop can also be used to iterate over the elements of a set. Since sets do not contain duplicates, you don't need to worry about repeated values when using for...of.
Example:
const uniqueNumbers = new Set([1, 2, 3, 4, 5]);
for (let number of uniqueNumbers) {
console.log(number);
}

You can also try this code with Online Javascript Compiler
Run Code
Explanation:
In this example, the for...of loop iterates over the set uniqueNumbers. Each value in the set is logged to the console. Since sets only allow unique values, there will be no duplicates in the output.
Output:
1
2
3
4
5
This demonstrates the simplicity and effectiveness of iterating over sets using for...of.
5. Iterating Over an Object’s Properties using for...of
Although for...of is not directly applicable to plain objects in JavaScript (since objects are not iterable by default), we can use Object.entries(), Object.keys(), or Object.values() to make the object iterable. These methods return an array of entries, keys, or values, which can be iterated over using the for...of loop.
Example:
const person = {
name: 'John',
age: 30,
job: 'Developer'
};
for (let [key, value] of Object.entries(person)) {
console.log(`${key}: ${value}`);
}

You can also try this code with Online Javascript Compiler
Run Code
Explanation:
In this example, we use Object.entries(person) to convert the person object into an array of key-value pairs, which can then be iterated over using the for...of loop.
Output:
name: John
age: 30
job: Developer
This shows how you can iterate over an object's properties using for...of by converting it into a format that is iterable.
Why Use `for...of`?
The `for...of` loop is cleaner & more intuitive compared to traditional loops like `for` or `forEach`. It directly gives you the value of each element, so you don’t need to deal with indexes or callbacks.
Browser Support
When writing JavaScript code, it’s important to ensure that it works across different browsers. The `for...of` loop is a modern feature, so let’s take a look at its compatibility with various browsers.
Modern Browsers
The `for...of` loop is supported in all modern browsers, including:
- Google Chrome (version 38 and above)
- Mozilla Firefox (version 13 and above)
- Microsoft Edge (all versions)
- Safari (version 7 and above)
- Opera (version 25 and above)
If you’re working on projects for modern web applications, you can safely use `for...of` without worrying about compatibility issues.
Older Browsers
However, if your project needs to support older browsers like Internet Explorer (IE), you might run into problems. Internet Explorer does not support the `for...of` loop at all. In such cases, you’ll need to use alternative methods like the traditional `for` loop or `forEach` method.
Checking Browser Support
To check if a browser supports `for...of`, you can use tools like [Can I use](https://caniuse.com/) or write a simple test script:
try {
const testArray = [1, 2, 3];
for (const item of testArray) {
console.log(item);
}
console.log("for...of is supported!");
} catch (error) {
console.log("for...of is not supported!");
}
Explanation:
- This script tries to run a `for...of` loop on a test array.
- If the browser supports `for...of`, it will log the numbers & the message "for...of is supported!".
- If the browser doesn’t support it, it will catch the error & log "for...of is not supported!".
Polyfills for Older Browsers
If you must support older browsers, you can use polyfills or transpilers like Babel to convert modern JavaScript code (including `for...of`) into older versions that work everywhere.
Frequently Asked Questions
What is the main difference between for...of and for...in loops in JavaScript?
The for...of loop iterates over the values of an iterable object (like arrays, strings, sets), while the for...in loop iterates over the keys (property names) of an object.
Can I use for...of to iterate over an object directly?
No, plain objects are not iterable. However, you can use Object.entries(), Object.keys(), or Object.values() to convert an object into an iterable form and then use for...of.
Is for...of better than the traditional for loop?
It depends on the use case. The for...of loop is simpler and more readable, especially when you need to iterate over collections like arrays, strings, maps, and sets. However, if you need the index or have more complex looping conditions, the traditional for loop may be better.
Conclusion
The for...of loop is a powerful tool for iterating over various data structures in JavaScript. Whether you're working with arrays, strings, maps, sets, or even object properties, this loop simplifies the process, making your code cleaner and more readable. In this article, we have discussed how to use for...of effectively in different contexts, and now you can apply this knowledge in your JavaScript projects with confidence.
You can also check out our other blogs on Code360.