JavaScript AcademyProfessional Engineering

Learning object 22 of 100

Reduce accumulator explorer

Follow the accumulator through every call of reduce: what came in, which item was combined, and what was passed on.

Loading…

What it shows

reduce calls your function with the accumulator (the result so far) and the next item, and whatever it returns becomes the accumulator for the next call. The initial value is the first accumulator. Without an initial value, reduce starts with the first item and skips calling the function for it, and an empty array then throws.

Guided experiment

  1. Run the total with initial value 0, then clear the initial value. How many calls happen now?
  2. Use (max, p) => p > max ? p : max to find the largest price.
  3. Count words with an object accumulator: start {} and callback (c, w) => ({ ...c, [w]: (c[w] ?? 0) + 1 }) on an array of words.

Predict

[5, 10, 15].reduce((t, n) => t + n, 0) calls the callback how many times?

Related

Lessons: Lesson 34: reduce and aggregation

Projects: Project 9: Shopping Cart Price Calculator

Source: web/assets/js/objects/object-022.js in the companion repository.