What's the difference between `map`, `forEach` and `for...of`?

poze 3 months ago296 gadeen

2

All three loop over an array. When should I pick which one? Is one faster?

Dyagnostik IA

Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.

poze 3 months ago

1 Repons

9
✓
✓ Repons yo aksepte

- 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.

Konekte pou di lòt moun si li te mache.

answered 3 months ago

Sign in and verify your email to post an answer.