Arrow functions are a shorter way to write functions. They were added in ES6 and are now the most common function syntax in modern JavaScript — especially in React.
Copy
// Regular functionfunction add(a, b) { return a + b;}// Arrow functionconst add = (a, b) => { return a + b;};console.log(add(3, 5)); // 8
Drop the function keyword, add => after the parameters. That’s it.
If your function does one thing and returns a value, use the implicit return. If it has multiple lines or side effects (like console.log), use curly braces with an explicit return.
When an arrow function has exactly one parameter, you can drop the parentheses:
Copy
// With parenthesesconst double = (n) => n * 2;// Without parentheses — same thingconst double = n => n * 2;// Zero parameters — parentheses requiredconst getTimestamp = () => Date.now();// Multiple parameters — parentheses requiredconst add = (a, b) => a + b;
Some teams require parentheses around all parameters for consistency. Either style is fine — Prettier will handle this for you based on your config.
Arrow functions have a technical difference with this binding, but you won’t encounter it in this course. React function components and hooks don’t rely on this, so it’s a non-issue. If you’re curious, MDN has a detailed explanation.
// Arrow functions can have multiple linesconst calculateTotal = (price, taxRate) => { const tax = price * taxRate; return price + tax;};// Or a single expressionconst double = n => n * 2;// Used as callbacksconst prices = [10, 20, 30];const withTax = prices.map(p => p * 1.08);
Copy
# Lambdas are limited to one expressiondouble = lambda n: n * 2# For anything more, you need defdef calculate_total(price, tax_rate): tax = price * tax_rate return price + tax# Used as callbacksprices = [10, 20, 30]with_tax = list(map(lambda p: p * 1.08, prices))
JavaScript’s arrow functions are more versatile than Python’s lambdas. They can have multiple lines, multiple statements, and they’re used far more often because JavaScript relies heavily on callbacks.
// ❌ Wrong: Curly braces but no returnconst double = (n) => { n * 2; // This computes but doesn't return anything};console.log(double(5)); // undefined// ✅ Correct: Either add return...const double = (n) => { return n * 2;};// ✅ ...or use implicit return (no curly braces)const double = (n) => n * 2;
With curly braces, you must use return. Without curly braces, the return is implicit. Mixing these up is the most common arrow function mistake.
Returning an object literal
Copy
// ❌ Wrong: JavaScript thinks {} is a function bodyconst getUser = () => { name: "Sarah", age: 28 }; // SyntaxError// ✅ Correct: Wrap the object in parenthesesconst getUser = () => ({ name: "Sarah", age: 28 });console.log(getUser()); // { name: "Sarah", age: 28 }
When implicitly returning an object, wrap it in parentheses (). Without them, JavaScript interprets the curly braces as a function body, not an object.