Skip to main content

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)
  • Map and Set objects
  • 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 cherry

Here, 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

Comparisonforfor...of
What it iterates overIndexes (numbers)Element values
Good forarrays with indexes, when you need a counterarrays, strings, Set, Map, any iterable structures
Access to the indexAvailable via the counter (i)Not directly (but can be counted separately if needed)
How concise it isMore "noisy"More readable and shorter
Works with objectsNo (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...of iterates over values
  • for...in iterates 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...of when you just need to walk through the values of an array, string, Set, or Map.
  • Use a regular for when you need indexes, control over the step, or an exit condition.
  • Use for...in when you are iterating over an object's keys.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.