void: functions that return nothing
Write functions that do a job and give nothing back: the return type void, the undefined their call leaves behind, leaving early with return;, and actions handed to forEach.
Tested with TypeScript 7.x · Node.js LTS
Most of the cards in your grandmother's drawer end with something
to hand over: twelve pancakes. One card ends differently. It says
Lay the table: plates, forks, the syrup in the middle. When you
have followed it, there is nothing to hand to anyone. The table is
laid, and that was the whole point. Many functions are like that
card, and console.log is one of them.
In lesson 1.2 you typed console. at Node's prompt,
and Node answered TaskKit, then undefined. Lesson 3.3 said
console.log gives back no value of its own, and that Module 5
explains where such answers come from. The last lesson promised to
show what TypeScript says such functions return. In this lesson you
write your own, mark them with the return type void, which says
they give nothing back, see what their call still gives back, and
hand them to forEach, the array method made for them. By the end,
TaskKit's list will be printed by one function whose type says so.
Every function you have written so far answered a question.
capitalize gives back the task with a capital letter, isCall
gives back true or false, percentFull a number. The call's
place is taken by that answer, and you keep it in a box or hand it
on. But much of what a program does is not an answer. Printing a
line, adding a task to a list: the work is done, and there is
nothing left to hand back.
Here is a function whose whole job is to print one task:
function printTask(task: string): void {
console.log(`- ${task}`);
}Its body has no return, and its return type is a new word,
void: the return type of a function that gives nothing back.
It tells everyone who reads the first line, and TypeScript, that
you call this function for what it does, not for an answer. Set
beside capitalize from lesson 5.1, the two kinds look like this:
- bread: the work is done inside the callRun it. Each call is a line on its own, with nothing in front of it to catch an answer:
It prints - buy milk and - call mom. If you leave : void out,
TypeScript works it out from the body, as it works out a box's type
from its value: rest the pointer on printTask in VS Code (Visual
Studio Code, your editor) and the hover says
function printTask(task: string): void. Write it anyway, for the
same reason you write : number on percentFull. It is a promise,
and TypeScript holds the body to it. Here a body that should only
print hands its task back as well:
Run it, and TypeScript refuses it with TS2322 (TS for TypeScript,
then the number of this kind of error):
Type 'string' is not assignable to type 'void'.: a value where you
promised none. Now read lesson 5.1's message once more, whole:
A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value. A function declared : void may end
without a return. A function declared : number may not.
'undefined' and 'any' are on that list too; void is the one to
write for a function that only does a job.
A call always leaves something in its place. capitalize("bread")
becomes "Bread", and that is what goes into the box. Lesson 5.2
said a body without return gives back undefined. Keep the
answer of printTask("buy milk") in a box, to see where that value
comes from. Press Next step to follow it, or Play:
The fourth step, back on line 4, is the one to look at. The body ran
to its closing brace without a return, so JavaScript put
undefined in the call's place: the value lesson 3.3 described as
"nothing was ever put here". The two words belong together. void
is the type, a promise written in the first line, read by
TypeScript before anything runs. undefined is the value the call
really gives back when Node runs it.
Now press Step on the same program. While the body runs, the
Call stack column says global › printTask; on line 5 the call
is over and only global is left.
That is also the undefined Node's prompt printed after
console. in lesson 1.2: console.log's return type
is void too. A box that keeps the answer of a void call holds
nothing you can use, so you will rarely write one. The common
mistake at the end of this lesson is what happens when you do.
In lesson 5.1, return did two things at once: it handed a value
back, and it ended the call. A void function has nothing to hand
back, but it may still need to stop early, such as when the task is
empty. Write return with nothing after it:
It prints Skipped an empty task, then - buy milk. For the empty
task, line 4 ends the call, and line 6 never runs. Without the
return;, the empty task would print its skip line and then a lone
- as well.
A bare return; belongs in a void function. In a function that
promised : string, TypeScript refuses it with TS2322:
Type 'undefined' is not assignable to type 'string'.: the call
would give back undefined where a string was promised.
In lesson 5.4 you wrote countIf, which takes a rule,
(task: string) => boolean, calls it for every task, and uses its
answer. A function can just as well take an action: a callback
that does a job, and whose answer the function never uses. The action's
type ends in => void, "a function that takes a string and gives
back nothing":
It prints - buy milk and - call mom. eachTask calls action
once for every task, as countIf called rule, but there is no
if around the call, because there is no answer to look at.
eachTask itself is void too: it prints through its action and
hands nothing back.
You will rarely write eachTask yourself, because every array
already has it. forEach calls the function you hand it once
for every item, in order, and gives back nothing. filter is the
array method for a rule; forEach is the one for an action:
true keeps the taskfalse toThe green notes are the types of the functions you hand over. Hand
forEach your own function by its name, without parentheses, as
you handed isCall to filter, or write an arrow in place, as you
did for map, filter and find in Module 4:
It prints - buy milk, - call mom, then BUY MILK and
CALL MOM. When you want a new list, map and filter are still
the methods to reach for. forEach is for the jobs whose result is
not a list: printing, or adding each item to another list.
Now TaskKit's step for this lesson. The lines at the end of
index.ts that print the list from A to Z do a job and give nothing
back: a void function.
Open index.ts in ~/projects/taskkit. At the top of the file,
under sameTask, declare it, with those lines as its body:
Its parameter tasks hides the file's tasks inside it, as lesson
5.5 showed, which is what you want: it prints whatever list it is
given. Then, at the end of the file, replace those lines with a
call:
Check the file with tsc (the TypeScript compiler, which npx
starts) and run it:
npx tsc prints nothing: the file passes. Then TaskKit prints:
The same list, now printed by one line that says what it does.
This function stops early on an empty list. Count every line it
prints, and remember what a void call leaves in its place.
Predict
What is the last line this program prints?
A function that shows the right text on the screen looks finished. So it is easy to write one that prints its result, and only later, somewhere else, try to keep that result and use it.
Common mistake
Keeping the answer of a function that only prints
label was written to show a task with a dash in front, and it
does. Now you want the same text in capitals, so you keep what it
gives back:
npx tsc --noEmit --types node label.ts refuses it:
The first line is one line in your terminal, broken here to fit
the page. TS2339 is the number of this message: TS for TypeScript.
Property 'toUpperCase' does not exist on type 'void'.
The fix
Make label give the text back instead of printing it, and print
it where it is used:
It prints - BUY MILK.
You never wrote void in that file, yet the message names it.
TypeScript worked out label's return type from its body, which has
no return, so line was void. Run it anyway with
node label.ts: Node prints - buy milk, then stops with
TypeError: Cannot read properties of undefined (reading 'toUpperCase').
So when an error names void you never wrote, look at the function
you called: it gives nothing back. Decide what it is for. If a caller
needs its result, it answers: return the value and write its type.
If it only does a job, it stays void, and nobody keeps its result.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Each one runs in your browser. Press Check when you think you have it; if you are stuck, the hints come one at a time.
Recap · 3 questions
Check yourself
What does : void after a function's parentheses promise?
Check yourself
A void call has printed its line. What does it give back?
Check yourself
What does forEach do with what its action gives back?
0 of 0 answered.
Cheat sheet
void: functions that return nothing
What things are
| Word | What it means |
|---|---|
void | The return type of a function that gives nothing back |
undefined | What a call of a function declared : void gives back |
| Action | A callback handed over to do a job, not to answer |
forEach | Calls an action once for every item, in order |
Code
| Write | To |
|---|---|
): void { | Promise to give nothing back |
return; | End the call early, handing nothing back |
action: (task: string) => void | Take an action as a parameter |
today. | Run an action for every task |
today. | Hand forEach an arrow in place |
Rules
| Rule | What it means |
|---|---|
| Type and value | void is the type; undefined the value |
No return written | TypeScript works out void by itself |
A value in a void body | TS2322: not assignable to 'void' |
return; in : string | TS2322: 'undefined' is not a string |
A method on a void result | TS2339: does not exist on 'void' |
| An action that answers |
You can now write a function that does a job and gives nothing
back, say so with void, and stop it early with return;. You know
that its call still leaves undefined in its place, and why an
error can name void you never wrote. You can take an action as a
parameter and hand one to forEach.
Next is Breaking a problem into small functions, starting from
plain-language steps. TaskKit already has a handful of small
functions, some that answer and one, printList, that does a job.
There you start from a description in plain words of what a program
should do, and turn each step into a function of one kind or the
other.
Before you move on, try to keep what printList gives back. In
index.ts, change the call to const shown = printList(tasks);,
hover over shown, and read its type. Then put the plain call
back.
| Accepted, and its answer thrown away |
| Answer or do | Return what a caller needs; print the rest |
An action that answers
What does this program print?
const today = ["buy milk", "call mom", "pay rent"];
const done: string[] = [];
today.forEach((task) => done.push(task.toUpperCase()));
console.log(done);============================
TaskKit 0.1
Your tasks, in your terminal
============================
Added: Pay rent
Added: Call Mom
Added: Buy milk
Tasks added: 3 of 5, room for 2 more
List 60% full
Your list, A to Z:
1. Buy milk
2. Call Mom
3. Pay rentlabel.ts:5:18 - error TS2339: Property
'toUpperCase' does not exist on type 'void'.
5 console.log(line.toUpperCase());
~~~~~~~~~~~
Found 1 error in label.ts:5const task = capitalize("bread");Gives back "Bread"
printTask("bread");Gives back nothing: void
function printTask(task: string): void {
console.log(`- ${task}`);
}
printTask("buy milk");
printTask("call mom");function printTask(task: string): void {
console.log(`- ${task}`);
return task;
}
printTask("buy milk");function printTask(task: string): void {
console.log(`- ${task}`);
}
const result = printTask("buy milk");
console.log(result);function printTask(task: string): void {
if (task === "") {
console.log("Skipped an empty task");
return;
}
console.log(`- ${task}`);
}
printTask("");
printTask("buy milk");function printTask(task: string): void {
console.log(`- ${task}`);
}
function eachTask(
tasks: string[],
action: (task: string) => void
): void {
for (const task of tasks) {
action(task);
}
}
const today = ["buy milk", "call mom"];
eachTask(today, printTask);today.filter(isCall);(task: string) => boolean
today.forEach(printTask);(task: string) => void
function printTask(task: string): void {
console.log(`- ${task}`);
}
const today = ["buy milk", "call mom"];
today.forEach(printTask);
today.forEach((task) => console.log(task.toUpperCase())); task.toLowerCase() === newTask.toLowerCase();
}
function printList(tasks: string[]): void {
const byName = tasks.toSorted(alphabetical);
console.log("Your list, A to Z:");
for (let i = 0; i < byName.length; i++) {
console.log(`${i + 1}. ${byName[i]}`);
}
}const byName = tasks.toSorted(alphabetical);
console.log("Your list, A to Z:");
for (let i = 0; i < byName.length; i++) {
console.log(`${i + 1}. ${byName[i]}`);
}
printList(tasks);function report(tasks: string[]): void {
if (tasks.length === 0) {
console.log("Nothing to do");
return;
}
console.log(`${tasks.length} to do`);
}
report([]);
console.log(report(["buy milk", "call mom"]));function label(task: string) {
console.log(`- ${task}`);
}
const line = label("buy milk");
console.log(line.toUpperCase());function label(task: string): string {
return `- ${task}`;
}
const line = label("buy milk");
console.log(line.toUpperCase());function printTask(task: string): void {
console.log(`- ${task}`);
}
const result = printTask("buy milk");
console.log(result);Line 4 calls printTask with "buy milk". The computer leaves the
line half done and goes into the function.
A fresh box task holds "buy milk", and the body prints its
line. That is the whole job of printTask.
- buy milkThe closing brace: the body is over, and no return handed
anything back.
Back on line 4, the call's place holds undefined, and it goes
into result. The box task is gone with the call.
Line 5 prints what the call gave back: undefined.
undefinedSay that printList gives nothing back
TypeScript refuses this program with A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value. printList only prints. Change its return type, and
nothing else, so that it prints both tasks.
Loading the editor…
Skip a blank task
This program prints a - and a row of spaces for a task that is only
spaces. Make printTask print Skipped a blank task for it instead,
and nothing else, by leaving the call early. The output should be
- buy milk, Skipped a blank task, - call mom.
Loading the editor…
Write remind and hand it to forEach
Write a function remind that takes a task and prints
Don't forget: before it, and gives nothing back. Write the types
of its parameter and of what it gives back. The lines that use it
are already there; they print one reminder per task.
Loading the editor…
npx tsc --noEmit --types node index.ts
node index.ts add "pay rent" "call Mom" "buy milk"