Lesson 2 · Unit 08
Closures and iterators
Functions that remember, and values made on demand
What you practise
- Closures that keep state, functions that return functions, updating without mutating, generators and anything
for...ofcan loop over
Try a question from this lesson
Pick one
The outer function returns an arrow function, and that arrow function is then called three times. What prints?
function makeCounter() {
let count = 0;
return () => {
count += 1;
return count;
};
}
const next = makeCounter();
next();
next();
console.log(next());Correct answer
3
Why
The arrow function still sees count, the variable of the call that made it, long after that call has returned. The variable lives on because the function needs it. This pair is called a closure.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
A closure remembers
A closure is a function plus the variables that were around it when it was made.
Those variables stay alive for as long as the function does, and nothing else can reach them. That gives a function a private memory, with no class in sight.
Every call of the outer function makes a fresh set of variables.
function makeCounter() {
let count = 0; // private to one counter
return () => {
count += 1;
return count;
};
}
const next = makeCounter();
console.log(next()); // 1
console.log(next()); // 2Concept
Update without changing
An array or object may be shared by many parts of a program. Change it, and you change it for all of them.
The safe habit is to build a new value with the change in it: spread to add or replace, filter to remove, map to change items. The old value stays valid for whoever still holds it.
const cart = ["tea", "jam"];
const more = [...cart, "rice"];
const less = cart
.filter((x) => x !== "jam");
const user = { name: "Ada", age: 36 };
const older = { ...user, age: 37 };
console.log(cart.length, user.age);
// 2 36Concept
Generators
A generator function is written function*. It can pause. Each yield hands out one value and waits there until someone asks for the next.
for...of does the asking, until the generator runs out. The values are made one at a time, on demand, and no array is ever built.
function* countdown(from) {
for (let n = from; n > 0; n -= 1) {
yield n;
}
}
for (const n of countdown(3)) {
console.log(n);
}
// 3
// 2
// 19 more exercises in the app
- 3× type the answer
- 2× fill the blanks
- 2× multiple choice
- 1× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.