In this lesson, you added up Rosa’s ratings again, this time with .reduce() instead of a loop. You saw what goes wrong when you leave out the starting value, traced the fixed call one call at a time, and watched each return become the next call’s accumulator.
Key Points
- The loop version starts a total at
0, adds each book’s rating, and logs14for Rosa’s three books: Parable of the Sower (5), Little Fires Everywhere (4) and Project Hail Mary (5). - Instead of a
letthat changes inside a loop,.reduce()hands back the total as one value, ready to store in aconst, the way.map()hands back a new array. - Like
.map(),.reduce()takes a function. It calls that function for the items, one after another, and passes it the running total first, then the current item, plus two extras you can ignore for now. Whatever the function returns becomes the running total for the next call. - Watch out for a call with no starting value.
rosa.books.reduce((total, book) => total + book.rating)logs[object Object]45, not14, and no error warns you. With no starting value,.reduce()takes the first book itself as the starting total and calls the function from the second book on. - Traced call by call, the first call adds
4to Rosa’s first book, the whole object. When you add a number to a plain object like Rosa’s first book, JavaScript turns it into the text[object Object]and joins the number on as text, so the call returns"[object Object]4". That text is the total for the second call, and the5joins on too. - On an empty list, such as Luis’s
books, the same call has no first item to start from, so it stops withTypeError: Reduce of empty array with no initial value. The initial value is the starting value you left out. - The fix is a second argument after the function: the starting value,
0. Traced again, the first call gets0and returns5, the second gets5and returns9, and the third gets9and returns14. When no items are left,.reduce()gives back the last return. - The running total is called the accumulator. Each call’s return becomes the next call’s accumulator.
- So your function has to return it. A one-line arrow function returns its expression for you. Written with braces and no
return, as inrosa.books.reduce((total, book) => { total + book.rating; }, 0), each call returnsundefined, the next call’s accumulator isundefinedtoo, and so is the result. - With a starting value of
0, Luis’s call logs0. With no books, the function never runs, so.reduce()gives back the starting value. - The rule: always pass the starting value. It makes the first call start from the right kind of value, and it gives an empty list a result instead of an error.
Final Code
The script report.js holds the club’s full log. Below it, Rosa’s and Luis’s totals each come from .reduce() with a starting value of 0. Copy it to follow along with the video: