— This is clearer, but it looks like there is at least one extra line.
— It’s good that you pay attention to the extra code. The assignment
sum = prev makes the
for loop example as similar as possible to the previous one with
— Can you elaborate on the “initial value” that we pass as the second parameter?
— When the
reduce function starts, it only has the first element of the array, so you need to add an initial value to start the calculations. Most often, this is an empty string, null, or an empty object.
Let’s see what happens if you try to
reduce on an array of objects and don’t add an initial value.
Here’s an example of how you could calculate the total salary for the year of all employees of the company.