Bitpath

Lesson 2 · Unit 08

Closures and iterators

Functions that remember, and values made on demand

13 exercisesabout 3 min

What you practise

  • Closures that keep state, functions that return functions, updating without mutating, generators and anything for...of can 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?

JavaScript
function makeCounter() {
  let count = 0;
  return () => {
    count += 1;
    return count;
  };
}
const next = makeCounter();
next();
next();
console.log(next());

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.

JavaScript
function makeCounter() {
  let count = 0; // private to one counter
  return () => {
    count += 1;
    return count;
  };
}
const next = makeCounter();
console.log(next()); // 1
console.log(next()); // 2

Concept

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.

JavaScript
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 36

Concept

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.

JavaScript
function* countdown(from) {
  for (let n = from; n > 0; n -= 1) {
    yield n;
  }
}
for (const n of countdown(3)) {
  console.log(n);
}
// 3
// 2
// 1

9 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.

One email when Bitpath is ready to try. Nothing else. Privacy