Topic 34 of 87
for...of Loop
Overview
Introduced in ES6, the for...of statement loops through the values of an iterable object (Arrays, Strings, Maps, Sets, and NodeLists).
It is the modern, cleanest way to loop through arrays when you don't need the index (and unlike .forEach(), it fully supports break, continue, and await).
Syntax
Iterating an Array
javascript
const cars = ["BMW", "Volvo", "Mini"];
for (let car of cars) {
console.log(car); // Prints: "BMW", "Volvo", "Mini"
}Iterating a String
javascript
const language = "JS";
for (let char of language) {
console.log(char); // Prints: "J", then "S"
}Common Pitfalls
- Trying to use
for...ofon a standard Object{}. Plain objects are not iterable, so this throws a TypeError. Usefor...inorObject.keys()for objects.
Interview Questions
Q:
What is the key difference between
for...in and for...of?A:
for...in iterates over the KEYS (property names) of an object. for...of iterates over the VALUES of an iterable object (like an array or string).
Q:
Can you use
await inside a for...of loop?A:
Yes! Unlike .forEach(), for...of is a standard loop syntax, so you can safely use await inside it to execute async operations sequentially.
Real-World Example
Executing a series of asynchronous API calls sequentially, one after the other.
example
javascript
for (let userId of userIdsArray) {
// Will wait for each to finish before moving to the next
await fetchUserData(userId);
}Check Your Knowledge
Test your understanding of for...of Loop with these quick questions.