Scope and closures (basics)
See which boxes a function can reach from where it is written, then write functions that make functions and keep the boxes they use: a rule maker and a task numberer that remembers its count.
See which boxes a function can reach from where it is written, then write functions that make functions and keep the boxes they use: a rule maker and a task numberer that remembers its count.
Tested with TypeScript 7.x · Node.js LTS
In lesson 4.3 you taught TaskKit to refuse a task typed twice.
Before add keeps a task, it hands find a rule that compares
the tasks on the list, one by one, with the new one:
const newTask = capitalize(tidyTask);
const twin = tasks.find(
(task) =>
task.toLowerCase() === newTask.toLowerCase()
);Look at that rule closely. Its only parameter is task, and it
makes no box of its own. newTask was made on the line above,
outside the arrow. Yet the rule reads it every time find calls
it, and it works. Nothing in the course has said why yet.
Think of the pancake card once more. If it says "use the milk in
the blue jug", it only makes sense in your kitchen, where the jug
is. Hand the card to a friend, and the jug has to go with it. In
this lesson you find out which boxes a function can reach from
where it is written, and what happens to them when the function is
handed on. By the end you will have a function that makes rules
for you, makeRule("call"), and one that numbers your tasks and
remembers where it got to.
You already know half of this. A box made inside a block exists
only up to that block's closing brace: an if in lesson 3.1, a
loop's task in lesson 4.2, a parameter that lives only while its
call runs in lesson 5.1. The part of the code where a name means
its box is called the box's scope. A box made in the file,
outside every function, has the whole file as its scope; a box
made inside braces has only those braces.
The other half is the direction you have used all along without a name: from inside the braces, looking out. Here is a function that works out how much room is left on the list:
const limit = 5;
function roomLeft(tasks: string[]): string {
const added = tasks.length;
if (added < limit) {
const free = limit - added;
return `Room for ${free} more`;
}
return "The list is full";
}
console.log(roomLeft(["buy milk", "call mom"]));Line 5 makes free out of two boxes it never made. added comes
from the function around it, and limit from the file around that.
Neither is passed in. When TypeScript meets a name, it looks for
its box in the nearest braces around the name first, and only when the
box is not there does it look one level further out. Press Next
step to follow it looking for limit, or let it play:
The if block: free
Not here. Only free was made inside these braces.
roomLeft: tasks, added
Not here. The function made tasks and added.
The file: limit, roomLeft
Found. limit is 5, made on line 1.
All 3 steps shown.
Run it:
const limit = 5;
function roomLeft(tasks: string[]): string {
const added = tasks.length;
if (added < limit) {
const free = limit - added;
return `Room for ${free} more`;
}
return "The list is full";
}
console.log(roomLeft(["buy milk", "call mom"]));It prints Room for 3 more. From inside, a function sees every box
around it: its own, those of any braces around it, and the file's.
From outside it is the other way round, as Module 3 showed: on line
10, added and free are unknown names.
The search starts inside and stops at the first box it finds. So a box inside can hide a box outside that has the same name:
const task = "pay rent";
function shout(task: string): string {
return `${task}!`;
}
console.log(shout("call mom"));
console.log(task);It prints call mom!, then pay rent. Inside shout, the nearest
task is its parameter, so the file's task is never looked at.
Outside, the parameter does not exist, and task is the file's box
again. Neither one changed the other. That is why every function in
this course can call its parameter task without trouble: each
function's task is its own. That is also why TaskKit's
percentFull(added, limit), from lesson 5.1, does not clash with the
file's boxes added and limit: inside it, the nearest added and
limit are its parameters.
One more rule: the search starts where the function is written, not where it is called. A function written in the file looks in its own braces, then in the file, wherever the call comes from. A box made inside another function is out of its reach, even when that other function is the one calling it. The common mistake below shows it as an error.
In lesson 5.4 you wrote isCall and isBuy, two functions that
differ in one word, and a third kind of task would mean a third
copy. You can write one function that makes them instead: hand it
the word, and it hands back the rule.
function makeRule(
word: string
): (task: string) => boolean {
return (task) => task.startsWith(word);
}Read the first three lines the way lesson 5.4 taught you:
makeRule takes a string, and what it gives back has the type
(task: string) => boolean, a function that takes a string and
gives back a boolean. A function type works as a return type just
as it did for a parameter. The body is one line: return hands
back an arrow, without calling it. The arrow's task needs no type
written, because the return type already says it is a string.
The arrow uses word, which is not its own: it is the parameter of
makeRule. And by the time anyone calls the arrow, makeRule is
over. In lesson 5.1, a parameter existed only while its call ran.
Press Next step to see what happens to word this time, or
Play:
function makeRule(
word: string
): (task: string) => boolean {
return (task) => task.startsWith(word);
}
const isCall = makeRule("call");
console.log(isCall("call mom"));
console.log(isCall("buy milk"));Line 6 calls makeRule with "call". The computer leaves the line
half done and goes into the function.
A fresh box word holds "call". return hands back an arrow,
without running it.
makeRule is over, but word is still there: the arrow uses it.
The arrow is now in the box isCall. The Memory column shows
every box the program has, so word stands beside isCall, yet it
is not the file's box: only the arrow can reach it.
Line 7 calls the arrow, with a fresh task. It reads word, the
box it kept: "call mom" starts with "call".
The arrow gave back true, and line 7 prints it.
trueLine 8 calls the arrow again. word is still "call", and
"buy milk" does not start with it.
The arrow gave back false, and line 8 prints it.
falseStep 3 is the one to look at. makeRule has returned, and its box
word has not gone with it, because the arrow it handed back still
uses it. A function together with the boxes from outside it that it
uses is called a closure: the arrow closes over word and
carries it wherever it goes, like the jug that goes with the card.
Every call of isCall reads that same word, "call". Nothing else
can: a line of the file that says word is refused with
Cannot find name 'word'., because word was made inside
makeRule, out of the file's reach, and only the arrow made there
still holds on to it.
Now press Step on the same program. While the arrow runs, the
Call stack column says global › anonymous: your file called
the arrow directly, and makeRule is no longer on the stack at all.
It is anonymous, not isCall: an arrow takes its box's name only
when it is written straight into the box, as left was in lesson
5.2. This one was written after return, with no box, and only
reached isCall later.
function makeRule(
word: string
): (task: string) => boolean {
return (task) => task.startsWith(word);
}
const isCall = makeRule("call");
console.log(isCall("call mom"));
console.log(isCall("buy milk"));A made rule is a function like any other, so it fits wherever the
rules of lesson 5.4 did: hand it to countIf, or to filter.
function makeRule(
word: string
): (task: string) => boolean {
return (task) => task.startsWith(word);
}
function countIf(
tasks: string[],
rule: (task: string) => boolean
): number {
let count = 0;
for (const task of tasks) {
if (rule(task)) {
count += 1;
}
}
return count;
}
const today = ["call mom", "buy milk", "call the bank"];
console.log(countIf(today, makeRule("call")));
console.log(today.filter(makeRule("buy")));It prints 2, then [ 'buy milk' ]. This time the parentheses
after makeRule are right. In lesson 5.4, isCall() handed over
an answer where a function was wanted. Here the answer of
makeRule("call") is a function, and that is what countIf gets.
TaskKit's twin rule is a closure too. The arrow you hand find
closes over newTask, the box made on the line above it in the
add case. find calls the arrow from inside itself, far from that
case, and the arrow still reads the newTask it was written
next to.
To number tasks, something has to remember the last number. A
let count in the file would do it, but then any line in the file
could change it by mistake. A closure can keep the box where
nothing else reaches it: word above is only read, but a closure
can also change the box it keeps, and the change is still there at
the next call. Here is a function that makes a numbering function
for a list:
function makeNumbering(): (task: string) => string {
let count = 0;
return (task) => {
count += 1;
return `${count}. ${task}`;
};
}
const label = makeNumbering();
console.log(label("buy milk"));
console.log(label("call mom"));
const other = makeNumbering();
console.log(other("pay rent"));It prints 1. buy milk, 2. call mom and 1. pay rent.
makeNumbering takes nothing, so its parentheses are empty, like
divider in lesson 5.2, an arrow that takes nothing. It makes a box
count and hands back an arrow with a body in braces that adds 1 to
count and gives back the numbered task. label goes from 1 to 2
because count is not a fresh box at each call: it is the box the
arrow kept.
Then why does other start at 1 again? Each call of
makeNumbering runs its body again, and let count = 0; makes a
new box each time. Two calls, two closures, two boxes:
const label = makeNumbering();
console.log(label("buy milk"));
console.log(label("call mom"));Its own count: 2
count of otherconst other = makeNumbering();
console.log(other("pay rent"));Its own count: 1
label got toNothing outside can reach count either. It is a box of
makeNumbering, so the file cannot see it, and the only way to
change it is to call the arrow.
Now TaskKit's step for this lesson. A function can make the twin
rule, the way makeRule makes its rules, and the call then says
what it looks for.
Open index.ts in ~/projects/taskkit. At the top of the file,
under alphabetical, declare the function that makes the rule:
function alphabetical(a: string, b: string): number {
return a.localeCompare(b);
}
function sameTask(newTask: string): (task: string) => boolean {
return (task) =>
task.toLowerCase() === newTask.toLowerCase();
}Then, in the add case, write the check with it:
const newTask = capitalize(tidyTask);
const twin = tasks.find(
(task) =>
task.toLowerCase() === newTask.toLowerCase()
);
const twin = tasks.find(sameTask(newTask));sameTask(newTask) runs first and hands back an arrow that keeps
sameTask's own newTask, a parameter holding the same text as the
add case's box of that name: two boxes in two scopes. find then
calls that arrow on the tasks one by one, and stops at the first
one it says true to. Check the file with tsc (the TypeScript
compiler, which npx starts) and run it with a task typed twice:
npx tsc --noEmit --types node index.ts
node index.ts add "buy milk" "Buy milk"npx tsc prints nothing: the file passes. Then TaskKit prints:
============================
TaskKit 0.1
Your tasks, in your terminal
============================
Added: Buy milk
Already on the list: Buy milk
Tasks added: 1 of 5, room for 4 more
List 20% full
Your list, A to Z:
1. Buy milkThe second one is still refused, by a rule that now comes from a
function with a name, sameTask.
Two numberings, called in turn. Follow each one's own count.
Predict
What is the last line this program prints?
function makeNumbering(): (task: string) => string {
let count = 0;
return (task) => {
count += 1;
return `${count}. ${task}`;
};
}
const shopping = makeNumbering();
const calls = makeNumbering();
console.log(shopping("buy milk"));
console.log(calls("call mom"));
console.log(shopping("buy bread"));A function that is called from inside another one looks as if it were inside it. So it is easy to expect it to see that function's boxes.
Common mistake
Reading a box made in the function that calls it
report makes limit and calls isFull, so limit seems to be
right there when isFull runs:
function isFull(added: number): boolean {
return added >= limit;
}
function report(added: number): string {
const limit = 5;
if (isFull(added)) {
return "The list is full";
}
return `Room for ${limit - added} more`;
}
console.log(report(5));npx tsc --noEmit --types node report.ts refuses it:
report.ts:2:19 - error TS2304: Cannot find
name 'limit'.
2 return added >= limit;
~~~~~
Found 1 error in report.ts:2The first line is one line in your terminal, broken here to fit
the page. TS2304 is the number of this message: TS for
TypeScript.
Cannot find name 'limit'.
The fix
Make limit in the file, the place where both functions are
written, so both can see it:
const limit = 5;
function isFull(added: number): boolean {
return added >= limit;
}
function report(added: number): string {
if (isFull(added)) {
return "The list is full";
}
return `Room for ${limit - added} more`;
}
console.log(report(5));It prints The list is full.
isFull is written in the file, so it looks in its own braces and
then in the file. The limit inside report is in neither: it
exists only inside report's braces, wherever isFull is called
from. So when Cannot find name names a box you can see in the
file, look at where the function is written, not where it is
called. Move the box out to where both functions can see it, or
pass it in as a parameter.
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.
Two boxes called added
What does this program print?
const added = 3;
const limit = 5;
function percentFull(added: number, limit: number): number {
return Math.round((added / limit) * 100);
}
console.log(percentFull(1, 4));
console.log(added);Say what makeRule gives back
TypeScript refuses this program with Parameter 'task' implicitly has an 'any' type. Write the return type of makeRule, and change
nothing else, so that the program prints true.
Loading the editor…
Keep the count between calls
This program prints 1. buy milk and then 1. call mom. Fix it so
that it prints 1. buy milk and then 2. call mom.
Loading the editor…
Write shorterThan
Write a function shorterThan that takes a number, limit, and
gives back a rule: a function that takes a task and gives back
true when the task has fewer than limit characters. Write the
types of the parameter and of what it gives back. The lines that
use it are already there; they print [ 'buy milk', 'pay rent' ]
and then [].
Loading the editor…
Recap · 3 questions
Check yourself
Inside a function, where is a name looked for first?
Check yourself
Called from report, can isFull see report's boxes?
Check yourself
makeRule("call") has returned. What happens to its box word?
0 of 0 answered.
Cheat sheet
Scope and closures (basics)
What things are
| Word | What it means |
|---|---|
| Scope | The part of the code where a name means its box |
| Looking out | Own braces first, then outward to the file |
| A hidden name | A box inside with the same name wins inside |
| Closure | A function with the outside boxes it uses |
Code
| Write | To |
|---|---|
): (task: string) => boolean { | Promise to give back a function |
return ( | Return an arrow using word |
const isCall = makeRule("call"); | Make a rule and keep it in a box |
countIf(today, makeRule("call")) | Make a rule and hand it straight over |
let count = 0; before return | A box the arrow keeps between calls |
Rules
| Rule | What it means |
|---|---|
| Inside sees out | A function reads the boxes around it |
| Outside sees nothing in | A box in braces ends at their } |
| Written, not called | Where it is written decides what it reaches |
| A kept box lives on | After the call that made it is over |
| One box per call | Each makeNumbering() makes a new count |
| Out of reach | TS2304: Cannot find name |
No return type on makeRule | The arrow's task is any: TS7006 |
| Keep it outside the arrow | A box made inside is new at every call |
You can now say which boxes a function can use: its own, then those around it, out to the file, all decided by where it is written. You can write a function that makes and hands back another function, and you know that the boxes it uses go with it, read or changed, for as long as the function lives.
Next is void: functions that return nothing. Every function
in this lesson gave something back. There you write functions whose
whole job is to do something, such as print a line, and see what
TypeScript says they return.
Before you move on, run
node index.ts add "buy milk" "BUY MILK" "Buy Milk". Predict before
you press Enter how many tasks are added and which lines
say Already on the list.