javascript · level 3 · unit 1 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A is a function that carries its scope with it.
A function can be made inside another function and handed back with return. Here makeCounter builds a small function and returns it. A function that makes and returns new things like this is called a .
When makeCounter finishes, you might expect count to vanish. It survives, because the inner function still uses it. A function plus the variables it remembers is a closure, like a snail carrying its house wherever it goes.
Each call to the factory makes a fresh count, so two counters never share one.
function makeCounter() {
let count = 0;
return () => {
count++;
return count;
};
}
const nextTicket = makeCounter();
console.log(nextTicket());
console.log(nextTicket());
console.log(nextTicket()); () => { } is an arrow function: a short way to write a function with no name of its own.
guess first
Two counters from one factory. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function makeCounter() {
let count = 0;
return () => {
count++;
return count;
};
}
const cups = makeCounter();
const plates = makeCounter();
cups();
cups();
console.log(plates(), cups());
your turn
Your turn. Build a greeting factory.
Choose a greeting, such as Howdy or Good morning, for the first blank and a name for the second. Notice the second greeter call reuses the remembered greeting.
fix it
Every order is number 1. Can you fix it?
- The inner function runs on every call. What happens to
counteach time it runs? countis made inside the inner function, so every call starts it again at 0.- Move
let count = 0;up one level, abovereturn () => {, so the closure remembers it.
nailed it
your functions can remember now. :D
- A closure keeps the variables it could see when made.
- Each factory call makes fresh, separate memory.
- Keep the memory outside the inner function, or it resets.
new words in your collection
- closure
- factory
This lesson isn’t saved. A free account remembers every lesson you finish.