DEV Community

Discussion on: Stop using for loops. Here's why.

Collapse
lukaszahradnik profile image
Lukáš Zahradník • Edited on

Yeah, I wasn't specific, but I mentioned that loops are more flexible.

I really think that most of the times is reduce used/overused because it's "modern" and "cool".
There sure are use/edge cases, but how often do you come across them?
And they can be usually rewritten into loops easily with preserved or even improved readability.

Thread Thread
idanarye profile image
Idan Arye

+1 about reduce. Consider #3 in dev.to/thejohnstew/5-programming-p...

const exampleValues = [2, 15, 8, 23, 1, 32];
const [truthyValues, falseyValues] = exampleValues.reduce((arrays, exampleValue) => {
  if (exampleValue > 10) {
    arrays[0].push(exampleValue);
    return arrays;
  }

  arrays[1].push(exampleValue);
  return arrays;
}, [[], []]);

It uses reduce to feel functional and hip, but in practice it just mutates the arrays and passing them as is (they are mutated, but it's the same reference) to the next iteration.

But even proper uses of fold/reduce are usually clearer and simpler when done with loops, because the whole point of reduce was to emulate foreach in purely functional languages.