I came across a puzzle that I’m attempting to solve and I help in clarifying whether I’ve got a clear resolution.
So, there’s a challenge that could be solved by either reduce or forEach:
I solved with reduce and that solution I used a return statement on reduce as you do(arr.reduce((acc, cum)=>
).
I used the same return statement on forEach and it did not pass the challenge.
return arr.forEach((item)=>
So the return statement snagged something in the forEach’s functionality that caused the code not to work.
I researched a bit on reddit and I came up with this explanation for my own notes. I would like someone to tell me if what I’m saying is logical in relation to the functionality of reduce and forEach. If not, where have I misunderstood. Explanation is below. Thank you.
I think this is because in essence the reduce method aggregates all data in whatever specified to aggregate it and forEach simply executes the provided function linearly within the data. With reduce there appears to be more flexibility and so the return method works with reduce because it is a holistic method as oppose to forEach which will be very exact in execution upon data but does not step outside of that particular functionality.