Fold a whole list into one value with reduce: a rule that takes the total so far and the next item, and a start value it begins from. Add up the minutes of a day, add up something about every item, see why each answer comes back as the next total, and why leaving out the start value glues numbers onto text or stops Node on an empty list.
TypeScript
Fundamentals
`reduce`. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
The last lesson ended with a promise: reduce folds a whole list into
one value of your choosing: it combines every item into one result.
Here is a list that needs it. Today's tasks take 25, 15, 30 and 10
minutes, and you leave in an hour and a half. Do they fit? In lesson
4.2 you answered a question like this with a loop: a let box at 0,
and total += minute on every turn. None of the methods from lesson
4.3 can write that loop for you. They give back a list, one item, or a
yes or no, never a total.
Think of the till at a supermarket. Your shopping rides the belt
past it one item at a time, and its screen shows one number: the
total so far, which every item adds to. When the belt is empty,
that number is what you pay. By the end of this lesson you hand a
list a rule that does what the till does, choose the number it
starts from, and know why leaving that number out can stop your
program on an empty list.
The loop that keeps a running total
Start with the loop you already know. Run it:
total.tsts
const minutes = [25, 15, 30, 10];let total = 0;for (const minute of minutes) { total += minute;}console.log(total);
It prints 80, so the tasks fit, with ten minutes to spare. total
is a running total: a box that holds what has been added up so
far, the way the till's screen does. Read the loop as a job in
three parts:
A start. Before the first item, total holds 0.
A step for every item. Each turn adds one item to total.
One value at the end. When the items run out, total holds
the answer.
Lists have a method for this job too: reduce. Here is the
loop beside reduce doing the same job:
const minutes = [25, 15, 30, 10];let total =0;for (const minute of minutes) { total += minute;}
total starts at 0
A loop and a let box
Does: Adds every item to a box you made and keep refilling
Does: Walks the list and keeps the running total for you
Never: Never needs a let box or a loop of your own
The same total, kept by a loop and by reduce
You hand reduce two things, separated by a comma: a rule, and
the value the total starts from. The rule does what the loop's
body did, and the 0 does what let total = 0 did. What reduce
gives back, the finished total, goes into a box of its own,
planned. There is no let box to refill, so planned can be a
const.
A rule that gets the total so far
The rule is an arrow function with two names, like the compare
functions of lesson 4.4:
ts
(total, minute) => total + minute
This time the two names are not two items of the list. The first
is the running total so far; the second is the next item. The rule
gives back the new total: here, the total so far plus this item.
reduce keeps that answer, and on the next call hands it back to
the rule as total. When no items are left, the last answer is
what reduce gives back.
The value after the rule is the start value: what total holds
on the very first call, before any item has been added. TypeScript
gives total the type of the start value, number for 0, and
minute the type of the list's items, so you write no types here
either.
Here are the four calls reduce makes for today's list. As in
lesson 4.4, a solid arrow is a question to the rule and a dashed
one is its answer, and the box at the end is what reduce does
when the items run out. Press Next step to follow them, or let it
play:
reduce
(total,minute)=>total+minute
1
reduce to (total, minute) => total + minute: total=0,minute=25
2
(total, minute) => total + minute to reduce: 25
3
reduce to (total, minute) => total + minute: total=25,minute=15
4
(total, minute) => total + minute to reduce: 40
5
reduce to (total, minute) => total + minute: total=40,minute=30
6
(total, minute) => total + minute to reduce: 70
7
reduce to (total, minute) => total + minute: total=70,minute=10
8
(total, minute) => total + minute to reduce: 80
9
reduce, to itself: Noitemsleft:givesback80
[25, 15, 30, 10].reduce(…, 0): each answer is the next total
All 9 steps shown.Step 1 of 9: reduce → (total, minute) => total + minute — total = 0, minute = 25Step 2 of 9: (total, minute) => total + minute → reduce — 25Step 3 of 9: reduce → (total, minute) => total + minute — total = 25, minute = 15Step 4 of 9: (total, minute) => total + minute → reduce — 40Step 5 of 9: reduce → (total, minute) => total + minute — total = 40, minute = 30Step 6 of 9: (total, minute) => total + minute → reduce — 70Step 7 of 9: reduce → (total, minute) => total + minute — total = 70, minute = 10Step 8 of 9: (total, minute) => total + minute → reduce — 80Step 9 of 9: reduce — No items left: gives back 80
All 9 steps shown.
Every answer is drawn twice: once coming back from the rule, and
once going in again as the next total. That is the whole idea of
reduce. The rule never sees the list, only the total so far and
one item, and that is enough to fold a list of any length. Now run
it. Press Step, and the player stops on the rule's line on
every call, with that call's total and minute in the variables:
The rule and the start value are on lines of their own only so
that the player stops on the rule each time. Written on one line,
minutes.reduce((total, minute) => total + minute, 0) does the
same.
The start value decides what comes out
The total does not have to be made of the items themselves. Here
reduce adds up the characters of three tasks: the items are
strings, and the total is a number, because the start value is 0.
It prints 24: 0, then 8, 16 and 24. You can leave the start value
out, and for adding up numbers that even looks fine: reduce then
takes the first item as the start and begins with the second one,
so [25, 15, 30, 10] still adds up to 80. But the first item is
not always the kind of value the total should be.
With no start value, the first total is "buy milk", and the rule
starts with "call mom". "buy milk" + 8 is text plus a number,
which + glues together as text, the way lesson 2.3 showed:
"buy milk8". The next call glues on another 8.
Bad — no start value, so the total
starts as the first task and the lengths are glued on as text.
The first prints buy milk88, and neither TypeScript nor Node says
a word: with no start value, TypeScript reads the total as a
string, the type of the list's items, and gluing a number onto a
string is allowed. Give reduce a start value every time, of the
type you want to come out.
Predict before you run
An hour of meetings is already booked before the tasks begin.
Decide what this prints.
npx tsc prints nothing: the file passes. Then Node stops on line
2:
Outputtext
/Users/ana/projects/taskkit/today.ts:2const planned = minutes.reduce((total, minute) => total + minute); ^TypeError: Reduce of empty array with no initial value at Array.reduce (<anonymous>) at Object.<anonymous> (/Users/ana/projects/taskkit/today.ts:2:25) at Module._compile (node:internal/modules/cjs/loader:1761:14) at Object..js (node:internal/modules/cjs/loader:1893:10) at Module.load (node:internal/modules/cjs/loader:1481:32) at Module._load (node:internal/modules/cjs/loader:1300:12) at TracingChannel.traceSync (node:diagnostics_channel:328:14) at wrapModuleLoad (node:internal/modules/cjs/loader:245:24) at Module.executeUserEntryPoint [as runMain](node:internal/modules/run_main:154:5) at node:internal/main/run_main_module:33:47Node.js v24.11.1
C:\Users\ana\projects\taskkit\today.ts:2const planned = minutes.reduce((total, minute) => total + minute); ^TypeError: Reduce of empty array with no initial value at Array.reduce (<anonymous>) at Object.<anonymous> (C:\Users\ana\projects\taskkit\today.ts:2:25) at Module._compile (node:internal/modules/cjs/loader:1761:14) at Object..js (node:internal/modules/cjs/loader:1893:10) at Module.load (node:internal/modules/cjs/loader:1481:32) at Module._load (node:internal/modules/cjs/loader:1300:12) at TracingChannel.traceSync (node:diagnostics_channel:328:14) at wrapModuleLoad (node:internal/modules/cjs/loader:245:24) at Module.executeUserEntryPoint [as runMain](node:internal/modules/run_main:154:5) at node:internal/main/run_main_module:33:47Node.js v24.11.1
/home/ana/projects/taskkit/today.ts:2const planned = minutes.reduce((total, minute) => total + minute); ^TypeError: Reduce of empty array with no initial value at Array.reduce (<anonymous>) at Object.<anonymous> (/home/ana/projects/taskkit/today.ts:2:25) at Module._compile (node:internal/modules/cjs/loader:1761:14) at Object..js (node:internal/modules/cjs/loader:1893:10) at Module.load (node:internal/modules/cjs/loader:1481:32) at Module._load (node:internal/modules/cjs/loader:1300:12) at TracingChannel.traceSync (node:diagnostics_channel:328:14) at wrapModuleLoad (node:internal/modules/cjs/loader:245:24) at Module.executeUserEntryPoint [as runMain](node:internal/modules/run_main:154:5) at node:internal/main/run_main_module:33:47Node.js v24.11.1
One line is broken in two to fit the page. On newer versions of
Node the paths may start with file:///, the numbers in the
node: lines differ and one at line may be missing; the last line
shows your version.
TypeError: Reduce of empty array with no initial value
The fix
Give reduce a start value. An empty list then gives back the
start value itself, and the program prints Planned: 0 minutes:
Read it with the five questions from lesson 1.5: Node wrote it, on
line 2 of today.ts; the ^ marks reduce; what is wrong is the
TypeError line. The initial value it names is JavaScript's word
for the start value (MDN writes initialValue). This time the first
at line, at Array.reduce (<anonymous>), is inside reduce itself,
code you did not write; the next one, today.ts:2:25, is your line.
Skip the rest as before.
With no start value and no items, reduce has nothing to start from
and nothing to give back, so Node stops. TypeScript cannot warn you,
because an empty list of numbers has exactly the right type; it does
not know how many items the list will hold when the program runs.
Lists you fill while a program runs, like TaskKit's tasks, start
empty, so the start value is not optional in practice: write it every
time.
None of these tasks is over 45 minutes, so long is empty, and this
program stops with a TypeError. Fix it so it prints 0.
Loading the editor…
Exercise · Fix the error
Count the characters as a number
This program should print 27, the characters in the three tasks,
but it prints water plants411. Fix it.
Loading the editor…
Exercise · Write the code
Add up the day
Use reduce to make planned, the sum of minutes, then print it
as Today: 95 minutes.
Loading the editor…
Recap
Recap · 3 questions
Check yourself
What does reduce give back?
Check yourself
[25, 15, 30].reduce(…, 0): total on the second call?
Check yourself
What happens with no start value on an empty list?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
reduce
What things are
Word
What it means
reduce
A method that folds a list into one value
Running total
What has been added up so far
Start value
What the total holds on the first call
Code
Write
To
.reduce(rule, 0)
Fold the list into one value, starting at 0
(total, minute) => …
The rule: the total so far and the next item
total + minute
Add the item to the total
total + task.length
Add up something about each item
Rules
Rule
What it means
Each answer goes back in
The rule's answer is the next call's total
Start sets the type
0 gives a number; with none, the first item
Always give a start
Without one, an empty list is a TypeError
TypeScript stays quiet
Glued text and the empty-list stop pass tsc
Where to go next
You can now fold a list into one value with reduce: add up
numbers, add up something about every item, and start the total
from any value you choose. You know why the start value is worth
writing every time, even when leaving it out looks harmless.
Next is Simple tuples. Every list so far has held items of one
type. A tuple is a short list of a fixed length where each place
has a type of its own, such as a task and its minutes, side by
side.
Before you move on, go back to planned.ts, press Edit, and make
the list empty: const minutes: number[] = [];. Predict what it
prints, then run it. Then delete the line that holds only 0 and run
it again, and say in one sentence why only the second run stops.