JavaScriptEasy
How do you loop over objects and arrays?
By FrontendPro Editorial Team Updated 9/26/2026
#JavaScript
Answer
For arrays reach for for...of when you need the values and forEach/map when you are already thinking in transformations. For objects, turn it into an array first with Object.keys, Object.values or Object.entries, then loop that.
Arrays
js
const xs = [10, 20, 30];
for (const x of xs) {} // values, supports break/continue/await
xs.forEach((x, i) => {}); // cannot break out of it
for (let i = 0; i < xs.length; i++) {} // when you need the index arithmetic
xs.map(x => x * 2); // new array
xs.filter(Boolean); xs.reduce(fn, 0); // narrowing / folding
Objects
js
const user = { name: 'Mai', age: 30 };
for (const key of Object.keys(user)) {}
for (const [key, value] of Object.entries(user)) {}
The two traps
for...in walks inherited enumerable keys too, so anything added to a prototype shows up. If you must use it, guard with Object.hasOwn(obj, key). Object.keys has no such problem.
And for...of needs an iterable. arguments and a NodeList are iterable; a plain object is not, which is why you cannot write for (const x of user).
Picking one
| Need | Use |
|---|---|
break early, or await inside | for...of |
| build a new array | map / filter |
| just side effects | forEach |
| key and value of an object | Object.entries |
Map or Set | for...of directly |
