I was practicing a reduce() exercise and this was the solution:
const reducemethod=(arr)=>{
return console.info(
arr.reduce((total, num,index)=>{
total=total+num;
if (index==arr.length-1){
return `The acumulation is ${total}`;
}
else {
return total;
}
})
}
My question is: why do we have to return 'total' in every reduce iteration? Does a parameter get lost when entering into a condition? (seems like this because if you don't return you get total as a NaN) Doesn't 'total' gets saved in the reduce function even if it enters into the condition? Thanks! Edit : Sorry I got a bad copy paste there, should be fixed now.
Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW
Comments
Post a Comment