Arrow Functions
Arrow functions are a shorter way to write function expressions, introduced in 2015 and now everywhere in modern JavaScript. Beyond saving keystrokes, they behave differently in one important way: they don't have their own this.
The syntax
const add = (a, b) => { return a + b; }; const addShort = (a, b) => a + b; const double = n => n * 2; const sayHi = () => "hi"; console.log(add(2, 3), addShort(2, 3), double(7), sayHi());
5 5 14 hi
The pieces:
- Parameters go before the
=>. With exactly one parameter, the parentheses are optional. With none, write(). - If the body is a single expression, drop the braces and the
return— the value is returned automatically ("implicit return"). - With braces, it's a normal function body and you need
return.
Returning an object
Braces after => are read as a function body, so to implicitly return an object literal, wrap it in parentheses:
const wrong = name => { name: name }; const right = name => ({ name: name }); console.log(wrong("Ana")); console.log(right("Ana"));
undefined
{ name: 'Ana' }Perfect for callbacks
Arrow functions shine when passing small functions to other functions:
const prices = [12, 7.5, 30, 4]; const doubled = prices.map(p => p * 2); const cheap = prices.filter(p => p < 10); const total = prices.reduce((sum, p) => sum + p, 0); console.log(doubled); console.log(cheap); console.log(total);
[ 24, 15, 60, 8 ] [ 7.5, 4 ] 53.5
Compare prices.filter(p => p < 10) with prices.filter(function (p) { return p < 10; }) — the arrow version reads almost like a sentence.
Arrow functions and this
A regular function gets its own this, set by how it's called. An arrow function doesn't — it uses the this of the code around it. That makes arrows ideal inside methods, but wrong as methods:
const timer = { seconds: 0, start() { [1, 2, 3].forEach(() => { this.seconds++; }); return this.seconds; }, arrowMethod: () => this?.seconds, }; console.log(timer.start()); console.log(timer.arrowMethod());
3 undefined
Inside start, the arrow callback sees start's this — the timer object — so this.seconds++ works. But arrowMethod has no this of its own, so this inside it isn't timer — it's whatever this was outside the object — and this?.seconds comes back undefined. Lesson 27 explains this fully.
Other differences
| Regular function | Arrow function | |
|---|---|---|
Own this | Yes | No — inherits it |
arguments object | Yes | No — use rest parameters |
Can be used with new | Yes | No |
| Hoisted | Declarations are | No (it's a variable) |
| Best for | Methods, constructors, top-level named functions | Callbacks and short helpers |
When to use which
A common modern style:
- Arrow functions for callbacks (
map,filter, event handlers, promises) and small utilities. - Method shorthand (
start() { … }) for methods on objects and classes. - Function declarations for important named functions at the top level of a file — they're hoisted and show up clearly in stack traces.