JavaScript gives us multiple ways to loop through data and execute repetitive tasks, each with its own strengths and ideal use cases:
for, while, do...while for...in, for...of .forEach(), .map(), .filter(), .reduce()
👉 Which one do you reach for the most in your projects?
Top comments (17)
Tbh I barely use just loops anymore. It's almost always
.map
in combination with filter or reduce if needed. If mapping is not required I useforEach
orfor of
depending on where the data comes from. If the data comes from a source outside of the source code, I always usefor of
for performance reasons. Oh and sometimes while loops when doing recursive stuff, like with generator functions.Using .map, .filter, and .reduce definitely leads to more declarative and readable code in most cases.
I don't use reduce anymore, instead I've adopted the habit of using Object.fromEntries:
I used to think using reduce was very fancy, imo now this is so much cleaner
reduce can be powerful but often feels a bit cryptic for building objects. Object.fromEntries + map is way more readable, especially for teammates going through your code later. Nice switch! 👌
for (const item of collection) {}
is the way to go :)for
orfor...of
if I'm looking for speed.map
, thenfilter
, thenreduce
by the look of things for data manipulation.nice, i always default to forEach out of habit but maybe i should branch out more - you ever feel like certain habits just stick even when you know there’s other options around?
ForEAch has specific usecase, you never modify arrays?
.filter()
.map()
await for
for...of
Because of eslint warning 😄
.map()
since I'm mostly writing React code.Honestly I hit forEach way too much by default, kinda stuck in my habits but it gets the job done every time.
forEach is super intuitive and readable, so it's easy to fall back on it.
I have never used
while
loop. In my code its mostly.map
because I mostly write Next code