The for of loop
What for...of does
The for...of loop is used to iterate over the elements of collections, such as:
- arrays (
Array) - strings (
String) MapandSetobjects- other iterable objects
It iterates over the values of the collection (not the indexes, like for does).
Example with an array
javascript
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
console.log(fruit);
}Result:
javascript
apple
banana
cherryHere, on each iteration fruit is the array element itself, not its index.
Example with a string
javascript
for (const char of "Hi!") {
console.log(char);
}Result:
javascript
H
i
!How it differs from a regular for
| Comparison | for | for...of |
|---|---|---|
| What it iterates over | Indexes (numbers) | Element values |
| Good for | arrays with indexes, when you need a counter | arrays, strings, Set, Map, any iterable structures |
| Access to the index | Available via the counter (i) | Not directly (but can be counted separately if needed) |
| How concise it is | More "noisy" | More readable and shorter |
| Works with objects | No (only with array-like structures) | No (you need for...in or Object.keys) |
Comparison example
A regular for:
javascript
const numbers = [10, 20, 30];
for (let i = 0; i < numbers.length; i++) {
console.log(i, numbers[i]); // i is the index, numbers[i] is the value
}for...of:
javascript
for (const num of numbers) {
console.log(num); // only the values
}Important not to confuse:
for...ofiterates over valuesfor...initerates over an object's keys (property names)
An example of the difference:
javascript
const user = { name: 'Oleh', age: 25 };
for (const key in user) {
console.log(key); // name, age
}
// for (const value of user) { } Error: the object is not iterable!When to use each
- Use
for...ofwhen you just need to walk through the values of an array, string, Set, or Map. - Use a regular
forwhen you need indexes, control over the step, or an exit condition. - Use
for...inwhen you are iterating over an object's keys.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.