Arrow Functions (ES6)
Arrow functions are a shorter syntax for writing functions introduced in ES6. They're used everywhere in modern JavaScript — callbacks, array methods, React components, and event handlers.
Arrow Function Syntax
- Basic — const add = (a, b) => { return a + b; }
- Implicit return — const add = (a, b) => a + b; (no braces = auto return)
- Single parameter — const double = n => n * 2; (no parentheses needed)
- No parameters — const greet = () => 'Hello!';
- Arrow vs Regular — Arrow functions don't have their own 'this' (inherits from parent scope)
- When to use — Callbacks, array methods (map, filter), short functions. NOT for object methods
Arrow Functions Code
// Regular function
function add(a, b) {
return a + b;
}
// Arrow function (same thing)
const addArrow = (a, b) => a + b;
console.log(addArrow(5, 3)); // 8
// Single parameter — no parentheses needed
const double = n => n * 2;
console.log(double(5)); // 10
// No parameters
const greet = () => "Hello, World!";
console.log(greet());
// Multi-line — need braces and return
const calculateTotal = (price, tax) => {
const taxAmount = price * tax;
const total = price + taxAmount;
return total;
};
console.log(calculateTotal(100, 0.18)); // 118
// ✅ Perfect for array methods
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
console.log(doubled); // [2, 4, 6, 8, 10]
console.log(evens); // [2, 4]
// ✅ Perfect for callbacks
setTimeout(() => console.log("Done!"), 1000);Tip
Tip
Use implicit return for short arrow functions: const double = n => n * 2. If you only have one expression, skip the braces and return keyword. This makes callbacks in map/filter much cleaner.
Function + environment.
Common Mistake
Warning
Using arrow functions as object methods breaks 'this'. const obj = { name: 'Alice', greet: () => console.log(this.name) } — this.name is undefined because arrow functions inherit 'this' from the outer scope, not the object.
Practice Task
Note
Convert these to arrow functions: (1) function square(n) { return n * n; }. (2) function isEven(n) { return n % 2 === 0; }. (3) Use your arrow functions with .map() and .filter() on an array of numbers.
Quick Quiz
Key Takeaways
- Arrow functions are a shorter syntax for writing functions introduced in ES6.
- Basic — const add = (a, b) => { return a + b; }
- Implicit return — const add = (a, b) => a + b; (no braces = auto return)
- Single parameter — const double = n => n * 2; (no parentheses needed)