Learn JavaScript · lesson 32 of 60 · about 8 minutes
Arrow Functions and Closures
Add a like button to the newest post: write compact functions with =>, and a function that remembers the likes between presses.
What you'll learn
- Write arrow functions
- Pass functions as values
- Understand closures
A like button
The newest post gets a like button. Each press should add one like and show the new total, so the button has to remember how many likes there are between presses. makeLikeButton(start) makes that button: it keeps the likes in a variable of its own and gives back a small function, press, that adds one and returns the total. Because press was made inside makeLikeButton, it can still reach that variable: it's a closure.
Arrow functions
(a, b) => a + b is a short way to write a function. With a single expression after =>, the value is returned automatically. With braces you need return.
Functions are values: you can store them in variables and pass them to other functions.
Arrows
const add = (a, b) => a + b;
const shout = (text) => text.toUpperCase() + "!";
const describe = (n) => {
const kind = n % 2 === 0 ? "even" : "odd";
return `${n} is ${kind}`;
};
console.log(add(2, 3));
console.log(shout("hi"));
console.log(describe(7));Output
5
HI!
7 is oddClosures
A function made inside another function remembers the variables around it, even after the outer function has finished. That's a closure. It's how you make private, persistent state.
A counter that remembers
function makeCounter() {
let count = 0;
return () => {
count++;
return count;
};
}
const next = makeCounter();
next();
next();
console.log(next());
const other = makeCounter();
console.log(other());Output
3
1Tip
newest?.likes ?? 0 reads likes only if newest exists: ?. gives undefined instead of crashing, and ?? swaps undefined for 0.
Now try it yourself
This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.