reduce
You'll learn to read reduce, which walks a list and builds up one value, like a total.
reduce in other people's code for totals and counts, so you need to read it calmly.Watch & read
Start with the required ones. The others are there when you need them.
Explanation
You want one answer from a whole list: the total of this month's expenses, or the total runs in an over.
map gives a list back and filter gives a list back. reduce gives back one value.
Think of a running total on a calculator. You start at 0. For each expense, you add it to what you have so far. At the end, the screen shows the total.
const expenses = [120, 80, 300];const total = expenses.reduce((sum, amount) => sum + amount, 0);// 500
The callback gets two things: the total so far, called the accumulator (here sum), and the current
item (amount). Whatever the callback returns becomes the new sum for the next item. The 0 at the end
is the starting value: what sum is before the first item.
Step by step: sum is 0, add 120, so 120. Add 80, so 200. Add 300, so 500. reduce returns 500.
People often forget the starting value. On an empty list that gives an error, and with objects it gives
strange results. Always pass one. With curly braces, people also forget return, and the total becomes
undefined.
This topic is optional for a reason. You will read reduce more than you write it. A for...of loop
with a let total = 0 does the same job and is often easier to read. When you meet reduce, find the
starting value, then ask: what does each step add to the total?
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1const runs = [4, 6, 1];2const total = runs.reduce((sum, r) => sum + r, 10);3console.log(total);
totalMarks should add up all the marks, and give 0 for an empty list. Two things are missing. Fix it so all three checks pass.Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3What does
reducegive back? - 2 / 3What is
[5, 10].reduce((sum, n) => sum + n, 100)? - 3 / 3In
list.reduce((sum, n) => sum + n, 0), what issum?
Explain it back
How confident are you with reduce?
Done
reduce call step by step and say what it returns.