Who reads the diary
Scope, nested functions and closures.
const city = "London";
function diary() {
const secret = "I love the vacuum";
console.log(city);
console.log(secret);
}
diary();
console.log(typeof secret);The rules are simple:
- a variable is visible in the
{ }block where it was declared, and in every nested one; - inner code sees outer variables; outer code does not see inner ones;
- each function call has its own local variables.
const fish = 3;
if (fish > 0) {
const message = "There is fish!";
let fish = 100; // its own fish, only inside the block
console.log(message, fish);
}
console.log(fish);
console.log(typeof message);fish hides the outer one. Outside it's 3 again, and message isn't visible at all.Why the fences at all? Long ago, every script on a page put its variables in one shared place. The visitor counter declared count, the cart declared count too, and suddenly the cart showed "1532 items". Scope is a fence: what's declared inside a function won't collide with someone else's code.
Now the trick. A function can create another function and return it. The inner function remembers the outer function's variables — even after the outer one has finished. That's a closure.
function makeCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
const next = makeCounter();
console.log(next());
console.log(next());
console.log(next());count lives between calls — and nobody but next can reach it.Why hide the counter inside a function when you could keep a plain variable outside? Compare two "Like" buttons.
let likes = 0;
function like() {
likes += 1;
return likes;
}
like();
like();
likes = -1000; // anyone can break it
console.log(like());
function makeLikeButton() {
let count = 0;
return () => {
count += 1;
return count;
};
}
const likeButton = makeLikeButton();
likeButton();
likeButton();
console.log(likeButton());likes. Nobody can reach count: only likeButton changes it.function makeGreeter(greeting) {
return (name) => `${greeting}, ${name}!`;
}
const hello = makeGreeter("Hello");
const meow = makeGreeter("Meow");
console.log(hello("Byte"));
console.log(meow("Mittens"));You can hand out more than one function — and they'll all share the same box. That gives you a small "object with a secret": you can use it, but you can't get inside.
function makeWallet(start) {
let money = start;
return {
pay: (sum) => {
if (sum > money) return "Not enough fish";
money -= sum;
return "Paid";
},
balance: () => money,
};
}
const wallet = makeWallet(50);
console.log(wallet.pay(30));
console.log(wallet.pay(30));
console.log(wallet.balance());
console.log(wallet.money);pay and balance see one money. And wallet.money is undefined: the object has no such property.Another common shape is a factory of configured functions. You set the configuration once, get a ready-made function and call it from then on without extra parameters. That's how a shop's discounts live: each promotion has its own percentage, but they're all computed the same way.
function makeDiscount(percent) {
return (price) => price - (price * percent) / 100;
}
const blackFriday = makeDiscount(30);
const forCats = makeDiscount(10);
console.log(blackFriday(1000));
console.log(forCats(1000));percent.useState), click handlers, debounce, counters, caches. A closure is a function with a backpack: inside are the variables from the place it was born.Pop quiz
Mistakes are fine: keep trying until you find the right answer, and Byte explains why it's right.