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

posée 3 months ago301 vuesen

2

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

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 3 months ago

1 réponse

9
✓
✓ Réponse acceptée

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

Connectez-vous pour dire si ça a marché.

answered 3 months ago

Sign in and verify your email to post an answer.