- Arrow functions are shorter than
function
- They inherit
this
from their scope (lexical)
- Great for one-liners and callbacks
Pattern |
Syntax |
Description |
Single param |
x => x * 2 |
Multiply by 2 |
Multiple params |
(a, b) => a + b |
Add two values |
No params |
() => 'Hello' |
Return a string |
Multi-line |
x => { const y = x * 2; return y; } |
Full block with return |
- Ideal for short, expressive callbacks
- Common with
.map()
, .filter()
, .reduce()
- Keeps your code concise
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((acc, n) => acc + n, 0);
numbers.forEach(n => console.log(n));
const firstEven = numbers.find(n => n % 2 === 0);
const hasEven = numbers.some(n => n % 2 === 0);
const allPositive = numbers.every(n => n > 0);
- Lexical
this
is perfect for React and DOM
- No need to bind methods manually
- Use for inline behavior
<button onClick={() => doThing()}>Click</button>;
document.getElementById('btn').addEventListener('click', () => {
console.log('Button clicked');
});
const handleSubmit = (e) => {
e.preventDefault();
console.log('Submitted');
};
- Keeps
.then()
chains readable
- Shortens boilerplate
fetch('/api/data')
.then(res => res.json())
.then(data => data.items.map(i => i.name))
.catch(err => console.error('Error:', err));
- Use
...args
to collect inputs
- Works well with
reduce()
const sum = (...nums) => nums.reduce((a, n) => a + n, 0);
const log = (...args) => console.log(args);
- Pull values right in the param list
- Works with objects and arrays
const getName = ({ name }) => name;
const getAgeText = ({ name, age }) => `${name} is ${age}`;
const getFirst = ([first]) => first;
const swap = ([a, b]) => [b, a];
- Arrow functions can run instantly
- Use for config or temporary logic
const result = (() => {
const secret = 'hidden';
return secret.toUpperCase();
})();
const config = ((key, base) => ({
key,
base,
url: `${base}/api`
}))('abc123', 'https://api.com');
- Arrow functions don't rebind
this
- Use them to retain object context
class Timer {
constructor() {
this.seconds = 0;
}
start() {
setInterval(() => {
this.seconds++;
console.log(this.seconds);
}, 1000);
}
}
- Regular functions have dynamic
this
- Arrow functions keep the outer
this
const obj = {
name: 'Object',
regularMethod() {
setTimeout(function () {
console.log(this.name);
}, 100);
},
arrowMethod() {
setTimeout(() => {
console.log(this.name);
}, 100);
}
};
β As Object Methods
const calculator = {
add: (a, b) => a + b,
multiply(a, b) { return a * b; }
};
β As Constructors
const Person = (name) => { this.name = name; };
function Person(name) {
this.name = name;
}
β In DOM Event Handlers
element.addEventListener('click', () => {
console.log(this);
});
element.addEventListener('click', function () {
console.log(this);
});
- New function is created each time
- Use named functions to reuse logic
const handlers = [];
for (let i = 0; i < 1000; i++) {
handlers.push(() => console.log(i));
}
const logIndex = (i) => console.log(i);
for (let i = 0; i < 1000; i++) {
handlers.push(() => logIndex(i));
}
- Arrow functions are not hoisted
- Must define before using
console.log(greet('John'));
const greet = (name) => `Hi, ${name}`;
console.log(greet('John'));
function greet(name) {
return `Hi, ${name}`;
}