I dont understand how the accumulator is working here in this simple reduce function. i understand accumulator is that after each iteration the accumulator value will be passed to the next iteration, i was expecting some thing like this … Any idea please if i am missing something here.
-
Expected output
as i understand reduce function
hellois odd // this return will be the accumulator for the next iteration
hellois odd is even // this return will be the accumulator for the next iteration
hellois odd is even is odd // this return will be the accumulator for the next iteration
hellois odd is even is odd is even // this return will be the accumulator for the next iteration
Reduce function on array17
const array17 = [1, 2, 3, 4];
function Evenodd(acc, element) {
if (element % 2 == 0) return `${acc}is even \n`;
else if (element % 3 == 0 && element % 2 != 0) {
return `${acc}is odd \n`;
} else if (element == 1) {
return `${acc}is odd \n`;
}
}
console.log(array17.reduce(Evenodd, "hello"));
Actual output in console
hellois odd
is even
is odd
is even