More JavaScript answers

by Danny
Published 2 min read

for...of loops over the values of arrays, strings, Maps and Sets. for...in loops over an object's keys, including inherited ones. Learn when to use each.

The short answer

#

Use for...of to loop over the values of an array, string, Map, Set or any other iterable. Use Object.entries with for...of to loop over a plain object. Avoid for...in on arrays: it gives you keys as strings, not values, and can include properties you did not expect.


_10
const fruits = ['apple', 'pear', 'plum'];
_10
_10
for (const fruit of fruits) {
_10
console.log(fruit); // 'apple', 'pear', 'plum'
_10
}
_10
_10
for (const index in fruits) {
_10
console.log(index); // '0', '1', '2' (strings)
_10
}

Why it happens

#

The two loops look alike but ask different questions.

  • for...in walks the enumerable string-keyed properties of an object, including ones inherited through the prototype chain. It was designed for objects, and it existed long before iterables.
  • for...of uses the iteration protocol. It asks the value for an iterator and reads values from it until it is done. Arrays, strings, Map, Set, arguments, NodeList and generators are all iterable. Plain objects are not.

That is why for...of on a plain object throws a TypeError saying the object is not iterable, and why for...in on an array returns '0', '1' and so on.

How to fix it

#

Arrays and other iterables: for...of

This gives you the values directly and works with break, continue and await.


_10
for (const user of users) {
_10
if (!user.active) continue;
_10
await sendReminder(user);
_10
}

If you need the index as well, use entries():


_10
for (const [index, fruit] of fruits.entries()) {
_10
console.log(index, fruit);
_10
}

Plain objects: Object.entries with for...of

Object.keys, Object.values and Object.entries return only the object's own enumerable properties, as arrays you can loop over.


_10
const prices = { tea: 2.5, coffee: 3, cake: 4.25 };
_10
_10
for (const [item, price] of Object.entries(prices)) {
_10
console.log(`${item}: £${price}`);
_10
}

Maps and Sets: for...of

A Map gives you [key, value] pairs in insertion order, and a Set gives you each value.


_10
const scores = new Map([['ada', 10], ['grace', 12]]);
_10
_10
for (const [name, score] of scores) {
_10
console.log(name, score);
_10
}

When for...in is still useful

for...in is fine for quickly inspecting the keys of a plain object you created yourself. If inherited properties might be present, filter them with Object.hasOwn.


_10
for (const key in options) {
_10
if (!Object.hasOwn(options, key)) continue;
_10
console.log(key, options[key]);
_10
}

In most code, Object.keys or Object.entries is clearer and does the filtering for you.

Common pitfalls

#
  • Using for...in on arrays. Keys are strings, so index + 1 gives '01', and extra properties on the array or its prototype show up too.
  • Using for...of on a plain object and getting "is not iterable". Loop over Object.entries(obj) instead.
  • Expecting forEach to wait for await. It does not; use for...of when each step must finish before the next.
  • Changing an array's length while looping over it. Copy it first, or build a new array with filter.
  • Relying on for...in order for numeric-looking keys. They are visited in ascending numeric order before other keys.
#

Was this resource helpful?