Arrow functions
Arrow functions are a shorter way to write functions, introduced in ES2015. They're everywhere in modern JavaScript, especially as callbacks.
JavaScript
// a regular function expression
const square1 = function (n) {
return n * n;
};
// the same as an arrow function
const square2 = (n) => {
return n * n;
};
// with an implicit return
const square3 = (n) => n * n;
console.log(square1(4), square2(4), square3(4));The shorthand rules
- One expression, no braces: the value is returned automatically (an implicit return).
- One parameter: the brackets are optional,
n => n * n. - No parameters: empty brackets are required,
() => 42. - Several statements: use braces and an explicit
return.
JavaScript
const greet = () => "Hello!";
const double = x => x * 2;
const add = (a, b) => a + b;
const describe = (name, age) => {
const status = age >= 18 ? "adult" : "minor";
return `${name} is an ${status}`;
};
console.log(greet(), double(21), add(2, 3), describe("Leo", 30));Returning an object
Braces after the arrow mean a function body, so wrap an object in brackets:
JavaScript
const makeUser = (name, age) => ({ name, age });
console.log(makeUser("Asha", 21));Perfect for callbacks
JavaScript
const prices = [120, 45, 300, 15];
console.log(prices.map(p => p * 1.18));
console.log(prices.filter(p => p > 50));
console.log([...prices].sort((a, b) => a - b));Arrow functions and this
Arrow functions don't have their own this; they use the this of the code around them. That makes them ideal inside methods, but a poor choice as methods:
JavaScript
const timer = {
seconds: 0,
start() {
// the arrow function sees the method's `this`, the timer object
const tick = () => { this.seconds++; };
tick(); tick(); tick();
console.log("seconds:", this.seconds);
},
broken: () => this === timer, // an arrow method doesn't see the object
};
timer.start();
console.log("arrow method sees timer?", timer.broken());Use regular method syntax (start() {}) for object methods and arrows for callbacks inside them.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.