Arrows are the default way to write callbacks in modern code.
An arrow function is a shorter function expression:
const double = (n) => n * 2;The rules for the short forms:
- One parameter: parentheses are optional (
n => n * 2); zero or several need them (() => 42,(a, b) => a + b). - If the body is a single expression without braces, its value is returned implicitly.
- With braces, it's a normal block and you need an explicit
return. - To implicitly return an object literal, wrap it in parentheses:
() => ({ id: 1 }). Without them, the braces are read as a block andid: 1as a label, so the function returnsundefined.
Arrows shine as callbacks: prices.map(p => p * 1.2), setTimeout(() => save(), 500).
They are not just syntax sugar, though. Arrow functions:
- have no own
this— they use thethisof the surrounding code, which is exactly what you want in callbacks inside methods; - have no own
argumentsobject (use rest parameters); - cannot be called with
newand have noprototype.
Because of the this behaviour, don't use an arrow as an object method that needs to refer to its object; use method syntax ({ total() { return this.a + this.b; } }) instead. You'll see the full this rules in a later lesson.
A common style is: function declarations for named, top-level functions, and arrows for short inline callbacks.
Example
const add = (a, b) => a + b;
const shout = s => s.toUpperCase() + "!";
const makeUser = name => ({ name, createdAt: 2025 }); // parens for object
console.log(add(2, 3)); // 5
console.log(shout("hey")); // HEY!
console.log(makeUser("Ada")); // { name: 'Ada', createdAt: 2025 }
const broken = () => { id: 1 }; // block with a label, not an object
console.log(broken()); // undefined
const prices = [10, 20, 30];
const withTax = prices.map(p => {
const tax = p * 0.2;
return p + tax; // braces need explicit return
});
console.log(withTax); // [ 12, 24, 36 ]Remember
x => exprreturnsexprimplicitly; a braced body needsreturn- Wrap object literals in parentheses:
() => ({ ... }) - Arrows have no own
this,argumentsorprototypeand can't be used withnew
Watch out for
- Using an arrow function as an object method and finding
thisisn't the object.