- Arrow functions are concise alternatives to
function
.
- No
function
keyword, and this
is inherited (lexical).
- Great for short, inline callbacks.
Pattern |
Syntax |
Example |
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 body |
- Arrow functions are perfect for functional array operations.
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);
- Use arrow functions to keep
this
lexical in callbacks.
<button onClick={() => handleClick()}>Click me</button>;
document.getElementById('btn').addEventListener('click', () => {
console.log('Button clicked');
});
const handleSubmit = (event) => {
event.preventDefault();
console.log('Form submitted');
};
- Use arrow functions for clean, chained
.then()
callbacks.
fetch('/api/data')
.then(response => response.json())
.then(data => data.items.map(item => item.name))
.catch(error => console.error('Error:', error));
- Use
...args
to collect multiple inputs into one array.
const sum = (...numbers) => numbers.reduce((acc, n) => acc + n, 0);
const logArgs = (...args) => console.log(args);
- Destructure objects and arrays right in the parameter list.
const getName = ({ name }) => name;
const getDetails = ({ name, age }) => `${name} is ${age} years old`;
const getFirst = ([first]) => first;
const swap = ([a, b]) => [b, a];
- Wrap in
()
to run immediately.
const result = (() => {
const secret = 'hidden';
return secret.toUpperCase();
})();
const config = ((apiKey, baseUrl) => ({
apiKey,
baseUrl,
endpoint: `${baseUrl}/api`
}))('abc123', 'https://api.example.com');
- Arrow functions inherit
this
from the surrounding scope.
class Timer {
constructor() {
this.seconds = 0;
}
start() {
setInterval(() => {
this.seconds++;
console.log(this.seconds);
}, 1000);
}
}
Regular vs Arrow Function (Context Differences)
- Regular functions get dynamic
this
.
- Arrow functions lock in
this
at definition time.
const obj = {
name: 'Object',
regularMethod: function () {
setTimeout(function () {
console.log(this.name);
}, 100);
},
arrowMethod: function () {
setTimeout(() => {
console.log(this.name);
}, 100);
}
};
- Don't use them as object methods, constructors, or when
this
is required dynamically.
Object Methods
const calculator = {
add: (a, b) => a + b,
multiply(a, b) { return a * b; }
};
const Person = (name) => { this.name = name; };
function Person(name) {
this.name = name;
}
element.addEventListener('click', () => {
console.log(this);
});
element.addEventListener('click', function () {
console.log(this);
});
- Each arrow function creates a new instance.
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.
console.log(greet('John'));
const greet = (name) => `Hello, ${name}`;
console.log(greet('John'));
function greet(name) {
return `Hello, ${name}`;
}