DEV Community

Discussion on: Reduce Vs For-Loop

Collapse
lukeshiru profile image
LUKESHIRU

The for snippet has some things missing:

  1. You can use for..of instead of for.
  2. You need to define singleVal before using it.

So a more fair comparison:

const array = [1, 2, 3];

// Reduce
const total = array.reduce((total, item) => total + item, 0);

// For..of
let total = 0;
for (const item of array) {
    total += item;
}
Enter fullscreen mode Exit fullscreen mode

For sums, usually the best approach is to just use a reduce. Choosing a for..of can be better in other scenarios, but for sums there isn't much to discuss.

Cheers!