Arrow functions
Overview
Arrow functions are a shorter way to write function expressions. Added in ES2015, they suit small callbacks and keep this from the code around them instead of creating their own.
// Function expression
const doubleFn = function (n) {
return n * 2;
};
// Same thing as an arrow function
const double = (n) => n * 2;They’re everywhere in modern JavaScript, especially as arguments to other functions:
const prices = [100, 250, 40];
const withTax = prices.map((p) => p * 1.18);
button.addEventListener('click', () => console.log('Clicked!'));Syntax
An arrow function drops the function keyword and puts => (read “goes to” or “arrow”) between the parameter list and the body.
Implicit return
When the body is a single expression, leave out the braces and return — the expression’s value is returned for you.
const square = (x) => x * x;
const isAdult = (age) => age >= 18;
const fullName = (first, last) => `${first} ${last}`;
const toUser = (name) => ({ name, active: true });Returning an object? Wrap it in parentheses. Without them, the braces are read as a function body and the function returns
undefined.
const bad = (name) => { name: name }; // returns undefined!
const good = (name) => ({ name: name }); // returns the objectBlock body
When you need several statements, use braces — and then you must write return yourself:
const describe = (score) => {
const passed = score >= 50;
const label = passed ? 'Pass' : 'Fail';
return `${label} (${score})`;
};Forgetting return inside braces is the most common arrow-function bug: the function runs but gives back undefined.
Parameters
With exactly one parameter the parentheses are optional. With none, or more than one, they’re required.
const shout = word => word.toUpperCase();
const greet = () => 'Hi!';
const add = (a, b) => a + b;
const withDefault = (name = 'friend') => `Hi ${name}`;
const sum = (...nums) => nums.reduce((t, n) => t + n, 0);Many teams (and Prettier, by default) always write the parentheses, (word) => …, for consistency. This course does the same.
Line breaks
The => must be on the same line as the parameters. A long implicit-return body can go on the next line:
const formatPrice = (amount, currency) =>
new Intl.NumberFormat('en-IN', { style: 'currency', currency }).format(amount);Arrow functions as callbacks
Their short form shines when a function is passed straight into another one. Compare:
// Regular function expression
const evens = numbers.filter(function (n) {
return n % 2 === 0;
});
// Arrow function
const evens = numbers.filter((n) => n % 2 === 0);Chained array methods read almost like a sentence:
const names = users
.filter((u) => u.active)
.map((u) => u.name)
.sort();How this works
Regular functions get their own this, set by how they’re called. Arrow functions don’t get their own this. They use the this of the surrounding code — wherever the arrow was written — which is why they’re handy for callbacks inside methods.
class Timer {
seconds = 0;
start() {
setInterval(() => {
this.seconds++; // `this` is still the Timer
}, 1000);
}
}With a regular function, the callback would get its own this (not the Timer) and this.seconds++ would fail. Before arrow functions, people wrote const self = this; or used .bind(this) to work around it. You’ll learn the full rules in Methods and this.
When not to use them
-
Object methods that need
thisto be the object. An arrow function would borrowthisfrom outside the object:JavaScript const counter = { count: 0, increment: () => { this.count++; }, // ✗ this is not counter add() { this.count++; }, // ✓ method shorthand }; -
Constructors — arrow functions can’t be called with
new. -
Functions that read the
argumentsobject — arrow functions don’t have one; use rest parameters (...args) instead. -
DOM event handlers that rely on
thisbeing the element. Useevent.currentTargetinstead, or a regular function. -
Functions you want hoisted. Arrow functions are stored in variables, so they only exist after the line that defines them.
Quick comparison
| Function declaration | Arrow function | |
|---|---|---|
| Syntax | function f(x) { return x; } |
const f = (x) => x; |
| Hoisted | Yes | No |
Own this |
Yes, depends on the call | No, uses surrounding this |
arguments object |
Yes | No |
Can use new |
Yes | No |
| Best for | Named, top-level functions; methods | Callbacks, small helpers |
Rewrite them as arrow functions
Turn each function into an arrow function, using an implicit return where you can.
function isEven(n) {
return n % 2 === 0;
}
function makeUser(name) {
return { name: name, active: true };
}const isEven = (n) => n % 2 === 0;
const makeUser = (name) => ({ name, active: true });Summary
(params) => expressionreturns the expression automatically.- Use braces and
returnwhen the body needs more than one statement. - Wrap an object literal in parentheses to return it implicitly.
- Arrow functions borrow
thisfrom where they’re written and have noarguments. - Use them for callbacks and small helpers; use regular functions for object methods and constructors.