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.
_10const fruits = ['apple', 'pear', 'plum'];_10_10for (const fruit of fruits) {_10 console.log(fruit); // 'apple', 'pear', 'plum'_10}_10_10for (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...inwalks 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...ofuses the iteration protocol. It asks the value for an iterator and reads values from it until it is done. Arrays, strings,Map,Set,arguments,NodeListand 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.
_10for (const user of users) {_10 if (!user.active) continue;_10 await sendReminder(user);_10}
If you need the index as well, use entries():
_10for (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.
_10const prices = { tea: 2.5, coffee: 3, cake: 4.25 };_10_10for (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.
_10const scores = new Map([['ada', 10], ['grace', 12]]);_10_10for (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.
_10for (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...inon arrays. Keys are strings, soindex + 1gives'01', and extra properties on the array or its prototype show up too. - Using
for...ofon a plain object and getting "is not iterable". Loop overObject.entries(obj)instead. - Expecting
forEachto wait forawait. It does not; usefor...ofwhen 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...inorder for numeric-looking keys. They are visited in ascending numeric order before other keys.
Related reading
#Was this resource helpful?