Watch the accumulator grow
The initial value sets the starting point and the type: 0 for a sum, 1 for a product, a string for joining text.
reduce walks through an array carrying one running value (the accumulator) and combines each item into it, turning a whole list into a single result such as a total, a count, a maximum or a grouped object; always give it a starting value.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Use reduce to find the total price of [{ name: "Pen", price: 20 }, { name: "Bag", price: 900 }].
Use reduce to turn [["a", 1], ["b", 2]] into { a: 1, b: 2 }.
Group [1, 2, 3, 4, 5] into { odd: [...], even: [...] } with Object.groupBy.
Explain it without notes
Explain how reduce works step by step for a sum.
What happens when you call reduce without an initial value?
How would you count how many times each word appears in an array?
When is a for...of loop better than reduce?
Console
(nothing was printed)Expected console output
acc = 0 n = 5
acc = 5 n = 10
acc = 15 n = 15
total: 30
product: 24
I learn every day