Think of a visit counter. Every time you call it, the number goes up: 1, 2, 3. The number has to be kept between two calls. But you don't want to put it in a global variable, because any code can change a global variable. A function can keep that number by itself.
Here is how. In JavaScript, you can make a function inside another function. The inner function still remembers the outer function's variables, even after the outer function has finished running. This is how you build counters, function factories (functions that make other functions), and data that can't be changed from outside.
A function that remembers its variables
Here is that visit counter as code. Its number is kept in count:
function makeCounter() {
let count = 0;
return {
inc: () => ++count,
peek: () => count,
};
}
const a = makeCounter();
const b = makeCounter();
a.inc();
a.inc();
console.log(a.peek()); // 2
console.log(b.peek()); // 0
console.log(a.count); // undefined
let count = 0makes the variablecountinsidemakeCounter.makeCounterreturns an object that holds two small functions,incandpeek.incruns++count: it adds one tocount, then returns the new value (1 on the first call, 2 on the second).peekonly readscount.makeCounter()has finished running beforeincis called. Butincandpeekcan still usecount, because both were made insidemakeCounter.- Every call to
makeCounter()makes a newcount, soaandbeach have their owncount.incis only called througha, so thecountofbstays at 0. a.countgivesundefined, becausecountis not a property of the objecta. From outside, you can only usecountthroughincandpeek.
The scope of count (the part of the code where count can be used) is the body of makeCounter. A function that still remembers the variables from the scope where it was made is called a closure. inc and peek are closures: both were made inside makeCounter, and both remember count.
In short: a function remembers the variables around the place where it was written. Every time the outer function is called, those variables are made new.
A function that returns a function
makeGreeting below is a function factory. makeGreeting takes a greeting, then returns a new function that uses that greeting:
function makeGreeting(greeting) {
return function (name) {
return greeting + ", " + name + "!";
};
}
const greetMorning = makeGreeting("Good morning");
const greetEvening = makeGreeting("Good evening");
console.log(greetMorning("Budi")); // Good morning, Budi!
console.log(greetEvening("Ani")); // Good evening, Ani!
console.log(makeGreeting("Hi")("Rina")); // Hi, Rina!
makeGreetingreturns a function, not text.greetMorningholds that function, and you can call it later.- The returned function remembers the
greetingfrom themakeGreetingcall that made it. SogreetMorningandgreetEveningeach have their owngreeting: one has Good morning, the other has Good evening. - In
makeGreeting("Hi")("Rina"), the first pair of brackets makes the function, and the second pair calls that function right away.
Methods that share one variable
Several closures can use the same variable. The shopping basket below keeps its items in the array items:
function makeBasket() {
const items = [];
return {
add(item) {
items.push(item);
},
count() {
return items.length;
},
};
}
const basket = makeBasket();
basket.add("book");
basket.add("pencil");
console.log(basket.count()); // 2
console.log(basket.items); // undefined
add(item) { ... }is the short way to write a method inside an object.- Both methods are made inside
makeBasket, so both use the sameitems. - From outside,
basket.itemsdoes not exist. So the basket's content can only change throughadd. Ifitemswere stored as a property of the object, any code could overwrite it.
⚠️ Why isn't the closure remembering the right thing?
- Putting the variable outside the function that makes things. A maker function is an outer function like
makeCounterormakeGreeting. If the variable is outside the maker function, every function it makes shares one variable, and the last value overwrites the earlier ones. Keep the value in a parameter or in aletinside the maker function. - Forgetting to
returnthe inner function. Withoutreturn,makeGreeting("Hi")givesundefined. ThenmakeGreeting("Hi")("Rina")causes an error, becauseundefinedis not a function and can't be called. =when you meant+=. In the second exercise,total = nonly keeps the last number, whiletotal += nadds that number to the old total.
🔬 Try it yourself
The tool below holds more closure patterns, from a private counter to the well-known loop bug. Pick one pattern, then see which variables its closure remembers.
TL;DR: A closure is a function that still remembers the variables from the scope (the part of the code) where it was made. It remembers them even after the outer function (the function it was made in) has finished running. Every call to the outer function makes new variables, so calling the counter maker makeCounter() twice gives two separate counts. Use a closure for functions that return functions (in makeGreeting("Hi")("Rina"), the second pair of brackets calls the returned function) and for data that can only change through the methods you provide.
⚡ A function that remembers its variables
Write:
function makeCounter() {
let count = 0;
return {
inc: () => ++count,
peek: () => count,
};
}
const a = makeCounter();
const b = makeCounter();
a.inc();
a.inc();
console.log(a.peek()); // 2
console.log(b.peek()); // ?
Guess first: inc adds one to count, and peek reads it. inc is called twice through a. What does b.peek() give?
0. Every call to makeCounter() makes a new count, so a and b each have their own count.
Meaning: makeCounter() has finished running, but inc and peek can still use count. A function that still remembers the variables from its outer scope (the part of the code where it was made) is called a closure.
⚡ No changing it from outside
Write:
console.log(a.count); // undefined
Meaning: count is a variable inside makeCounter, not a property of the object a. So from outside, you can only use count through inc and peek. If count were stored as a property of the object, any code could overwrite it.
⚡ A function that returns a function
Write:
function makeGreeting(greeting) {
return function (name) {
return greeting + ", " + name + "!";
};
}
const greetMorning = makeGreeting("Good morning");
console.log(greetMorning("Budi")); // Good morning, Budi!
Meaning: makeGreeting returns a function, not text. The returned function remembers the greeting from the makeGreeting call that made it. So you can call greetMorning at any time, and it always uses Good morning.