how does the index argument work in reducemethod in javascript?

The .reduce functions seems to initially assigns “acc” the type of the first element of what is being looped through, before it knows what you will be doing with it (could be math or string manipulation). You are trying to do math.

In the first case that type is a number, so all is well, but in the second, it is an object. Thus in the second case, you are adding a number (el.price) to an object ({name: “Bike”, price: 100}), thus converting it to a string. From here on out, you will just be concatenating strings rather then doing math.

By setting acc to 0, ur reassigning it a type of number, and thus it works.

So I think it is good practise to always assign acc in the reduce function to avoid these types of error.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top