What's the difference between `map`, `forEach` and `for...of`?
asked 3 months ago299 viewsen
All three loop over an array. When should I pick which one? Is one faster?
AI diagnosis
AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.
1 Answer
- map *transforms* an array into a new array of the same length. Use it when you want the result. ``js const names = users.map(u => u.name); ` - forEach runs a side effect for each item and returns undefined. You can't break out of it, and it does not wait for await inside the callback. - for...of is a normal loop. It supports break/continue, and await works as expected, sequentially: `js for (const id of ids) { await save(id); } ``
Rule of thumb: map/filter/reduce for data transformation, for...of for anything with control flow or await. Performance differences are irrelevant for normal array sizes.
Sign in to tell others whether this worked.
Sign in and verify your email to post an answer.