Morning Coffee
Looping in Javascript

Looping in Javascript

January 13, 2023
2 min read
Table of Contents

Looping in Javascript and Typescript

Javascript and Typescript have way too many ways to iterate and loop over arrays, objects, and iterables. In this post I try to collect them and make some sense of them.

ConstructEffect on arrayEffect on objectEffect on iterable (Map, Set)
for (let i=0;
  i<obj.length;
  i++)
★Iterates over indicesN/AN/A
for x in objIterates over indices and custom props (including prototype props), in random order(!)★Iterates over enumerable obj props (including prototype props)Iterates over Map keys; doesn’t work for Set
for x of obj★Iterates over values (in order)N/A 1★Iterates over [key, value] for Map, elements for Set
obj.forEach(x => ...)★Iterates over values (also passes index & array to callback) 2 3N/A 4★Map: iterates over values + keys 2

Notes:

Footnotes

  1. gives this error: “Error: obj is not iterable”. ↩

  2. .forEach() has no way to break out from the middle of the loop; the others ways of iterating over an array or object support break and continue. ↩ ↩2

  3. arr.forEach() does not work properly with await calls in the callback, but the others support await in the body. ↩

  4. obj.forEach() does not work on an Object, but you can do Object.keys(obj).forEach(...). That gets the keys of the object as an array, and then loops over the array of keys. ↩