Arrow Functions Explained
Arrow functions (=>) are a shorter way to write functions. They appear in React event handlers, array methods, and Node.js middleware. Every modern codebase uses them daily.
Syntax comparison
// Old way
function add(a, b) {
return a + b;
}
// Arrow function — same behavior
const add = (a, b) => a + b;
// Multiple lines — use { } and return
const greet = (name) => {
const msg = 'Welcome, ' + name;
return msg;
};
When to use arrow functions
- Callbacks:
items.map(item => item.price) - Short helpers:
const double = n => n * 2 - React:
onClick={() => setOpen(true)}
🌍 Real-world example — Filter paid invoices
const invoices = [
{ id: 1, amount: 500, paid: true },
{ id: 2, amount: 1200, paid: false },
{ id: 3, amount: 799, paid: true }
];
const paidTotal = invoices
.filter(inv => inv.paid)
.map(inv => inv.amount)
.reduce((sum, amt) => sum + amt, 0);
console.log(paidTotal); // 1299Arrow vs regular function — this
Arrow functions do not have their own this. They inherit this from the surrounding scope. That is why React class components used bind(), but functional components + arrows “just work”.
const timer = {
seconds: 0,
start() {
setInterval(() => {
this.seconds++; // ✅ this = timer object
}, 1000);
}
};
⚠️ Common Mistake: Using arrow functions as object methods when you need dynamic this — use regular function syntax for methods:
start() { } not start: () => { } in some cases.💡 Tip: If the body is one expression, you can omit return and braces:
x => x * 2.👨🏫 Teaching note: Have students rewrite three old function declarations as arrows — muscle memory before React.