Arrow Functions
The compact => function syntax, implicit returns, and the one big difference: arrow functions don't rebind this.
Arrow functions are a shorter way to write functions, introduced in ES6. They're everywhere in modern JavaScript — especially as callbacks passed to array methods and event handlers.
// traditional
function add(a, b) {
return a + b;
}
// arrow, with a block body
const add2 = (a, b) => {
return a + b;
};
// arrow, with an implicit return (no braces, no return keyword)
const add3 = (a, b) => a + b;#Concise bodies
If the body is a single expression, you can drop the braces and the return — the expression's value is returned automatically. With exactly one parameter you can even drop the parentheses.
const nums = [1, 2, 3, 4];
const doubled = nums.map(n => n * 2); // [2, 4, 6, 8]
const evens = nums.filter(n => n % 2 === 0); // [2, 4]
console.log(doubled, evens);Arrows don't have their own `this`
Unlike regular functions, an arrow function does not create its own this — it uses this from the surrounding scope. That's usually exactly what you want inside a callback (no more const self = this), but it means arrows are a poor choice for object methods that need to refer to the object via this.
What does `const square = n => n * n;` return when called as `square(5)`?
Rule of thumb: reach for arrow functions for short callbacks and helpers; use a regular function (or a class method) when you specifically need its own this or the arguments object.
Key takeaways
- Arrow functions are compact: `(a, b) => a + b`.
- A single-expression body returns that expression implicitly — no braces, no return.
- With one parameter, the parentheses are optional: `n => n * 2`.
- Arrows inherit `this` from the enclosing scope instead of creating their own — ideal for callbacks, wrong for object methods that need `this`.
What does this print?
const triple = n => n * 3;
console.log(triple(4));This arrow function should return an object literal, but it returns undefined. Why?
const makeUser = name => { name: name };
console.log(makeUser('Ada'));Complete the arrow function so it keeps only positive numbers.
const positives = nums.filter(n n > 0);
Rewrite this function as a one-line arrow function with an implicit return:
``js function greet(name) { return 'Hello, ' + name + '!'; } ``
Try it live — edit the code and hit Run to see the output: