# For vs forEach vs reduce

## Setup

``````const arr = [];

for (let i = 0; i < 100_000; i++) {
arr.push(i);
}``````

## Test runner

Testing in
TestOps/sec
One reduce loop
``````let sum2 = 0

const sum = arr.reduce((s, v) => {
sum2 += v - 1;
return s + v;
}, 0);``````
One reduce one forEach loop
``````let sum2 = 0

const sum = arr.reduce((s, v) => s + v, 0);

arr.forEach((v) => (sum2 += v - 1));``````
One for loop
``````let sum = 0;
let sum2 = 0;

for (let i = 0; i < arr.length; i++) {
sum2 += arr[i] - 1;
sum += arr[i];
}``````
Two for loops
``````let sum = 0;
let sum2 = 0;

for (let i = 0; i < arr.length; i++) {
sum2 += arr[i] - 1;
}

for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}``````
One forEach
``````let sum = 0;
let sum2 = 0;

arr.forEach((v) => {
sum2 += v - 1;
sum += v;
});``````
Two forEach
``````let sum = 0;
let sum2 = 0;

arr.forEach((v) => {
sum2 += v - 1;
});

arr.forEach((v) => {
sum += v;
});``````
While
``````let sum = 0;
let sum2 = 0;

let i = 0

while(i < arr.length) {
sum2 += arr[i] - 1;
sum += arr[i];
++i;
}
``````
For...of
``````let sum = 0;
let sum2 = 0;

for (const v of arr) {
sum2 += v - 1;
sum += v;
}
``````