Arrow Functions
An arrow function is a shorter way to write a function expression, using => instead of the function keyword: (days) => days * 2. Introduced in ES2015, arrows are now the usual way to write callbacks for array methods, timers and promises. They also behave differently in one important way: they don't have their own this, which fixes a classic bug and creates a new one if you use them in the wrong place.
In One Minute
(a, b) => a + bis an arrow function; with one parameter, parentheses are optional:x => x * 2.- With a single expression after
=>, its value is returned automatically (implicit return). With braces, you needreturn. - To return an object literal, wrap it in parentheses:
() => ({ total: 0 }). - Arrows have no own
this,arguments,superornew.target: they use the surrounding function's. - Use arrows for callbacks; use regular functions (or method shorthand) for object methods and constructors.
Syntax
(param1, param2) => expression // returns expression
(param1, param2) => { statements } // needs return
param => expression // one parameter: parentheses optional
() => expression // no parameters
() => ({ key: value }) // return an object literalExample
The same function written four ways, from longest to shortest:
const lateFeeA = function (days) {
return days * 2;
};
const lateFeeB = (days) => {
return days * 2;
};
const lateFeeC = (days) => days * 2;
const lateFeeD = days => days * 2;
console.log(lateFeeA(5), lateFeeB(5), lateFeeC(5), lateFeeD(5));10 10 10 10All four do the same thing. Form C, with parentheses and an implicit return, is the most common style (Prettier formats arrows this way by default).
Implicit Return
When the body is a single expression with no braces, its value is returned. As soon as you add braces, the body is a block of statements, and you must write return:
const withReturn = (x) => { return x * 2; };
const implicit = (x) => x * 2;
const forgot = (x) => { x * 2; };
console.log(withReturn(4), implicit(4), forgot(4));8 8 undefinedforgot has braces but no return, so it computes x * 2 and throws the result away.
Returning an Object Literal
Curly braces right after => are read as a block, not an object. To return an object, wrap it in parentheses:
const wrong = (name) => { name: name };
const right = (name) => ({ name: name, balance: 0 });
console.log(wrong("Navika"));
console.log(right("Navika"));undefined
{ name: 'Navika', balance: 0 }Explanation: in wrong, the braces are a block, and name: is read as a label (a rarely used feature from the break and continue lesson), followed by the expression name. Nothing is returned. The parentheses in right make it an expression.
Arrows as Callbacks
Arrows shine where a short function is passed to another function:
const payments = [
{ name: "Navika", amount: 120 },
{ name: "Srihitha", amount: 85 },
{ name: "Advitha", amount: 450 },
];
const names = payments.map((p) => p.name);
const large = payments.filter((p) => p.amount >= 100);
const total = payments.reduce((sum, p) => sum + p.amount, 0);
const sorted = [...payments].sort((a, b) => b.amount - a.amount);
console.log(names);
console.log(large.length, total);
console.log(sorted.map((p) => p.name).join(" > "));['Navika', 'Srihitha', 'Advitha']
2 655
Advitha > Navika > SrihithaCompare payments.map((p) => p.name) with payments.map(function (p) { return p.name; }). The arrow keeps the attention on what matters: "take each payment's name".
Arrows Have No Own this
Every regular function gets its own this value, set by how it is called. An arrow function doesn't: inside an arrow, this means whatever it meant in the code around it (it is lexically bound, from the surrounding scope). The this keyword has a full lesson in the advanced functions chapter; here is the part that affects everyday code.
Where Arrows Fix a Bug
A method that uses a callback inside it wants the callback to see the same this as the method. A regular function callback loses it; an arrow keeps it:
const tracker = {
owner: "Navika",
fees: [120, 85],
reportRegular() {
return this.fees.map(function (fee) {
return `${this?.owner}: ${fee}`;
});
},
reportArrow() {
return this.fees.map((fee) => `${this.owner}: ${fee}`);
},
};
console.log(tracker.reportRegular());
console.log(tracker.reportArrow());['undefined: 120', 'undefined: 85']
['Navika: 120', 'Navika: 85']Explanation: map calls the regular callback as a plain function, so its this isn't tracker (it is undefined in strict mode and modules, and the global object in older scripts), and the owner is lost. The arrow has no this of its own, so it uses the method's this, which is tracker. Before arrows, people wrote const self = this; before the callback, or used .bind(this).
Where Arrows Cause a Bug
For the same reason, an arrow is the wrong choice for an object's method. It doesn't get the object as this; it gets the this of the code where the object was written:
const student = {
firstName: "Advitha",
greetArrow: () => `Hi, ${this?.firstName}`,
greetMethod() {
return `Hi, ${this.firstName}`;
},
};
console.log(student.greetArrow());
console.log(student.greetMethod());Hi, undefined
Hi, AdvithaOther Differences
| Regular function | Arrow function | |
|---|---|---|
Own this | Yes, set by the call | No, uses the surrounding scope's |
arguments object | Yes | No (use ...rest) |
Can be called with new | Yes | No (TypeError: ... is not a constructor) |
Has a prototype property | Yes | No |
Can be a generator (function*) | Yes | No |
| Hoisted as a declaration | Yes (declarations) | No (always an expression) |
const Student = (name) => ({ name });
try {
new Student("Navika");
} catch (err) {
console.log(err.name + ": " + err.message);
}TypeError: Student is not a constructorIn Practice
The Fee Tracker's summary uses arrows for every data transformation, and a regular method where this matters:
const feeTracker = {
currency: "USD",
payments: [
{ name: "Navika", amount: 12000 },
{ name: "Srihitha", amount: 8550 },
{ name: "Navika", amount: 6000 },
],
totalsByStudent() {
const format = (cents) =>
new Intl.NumberFormat("en-US", { style: "currency", currency: this.currency }).format(cents / 100);
const totals = {};
this.payments.forEach((p) => {
totals[p.name] = (totals[p.name] ?? 0) + p.amount;
});
return Object.entries(totals).map(([name, cents]) => `${name}: ${format(cents)}`);
},
};
console.log(feeTracker.totalsByStudent());['Navika: $180.00', 'Srihitha: $85.50']totalsByStudent is a method (method shorthand), so this is feeTracker. The arrows inside it (format, the forEach and map callbacks) all see that same this.
Common Mistakes
Braces without return. (x) => { x * 2 } returns undefined. Remove the braces or add return.
Returning an object without parentheses. () => { a: 1 } returns undefined. Write () => ({ a: 1 }).
Arrow functions as methods. this won't be the object. Use method shorthand.
Very long arrow chains. A dense one-liner like a.map(x => x.b).filter(y => y > 2).reduce(...) is fine; three levels of nested arrows aren't. Name intermediate results.
Interview Corner
What are the differences between arrow functions and regular functions?
Arrows have no own this, arguments, super or new.target; they capture them lexically from the enclosing scope. They can't be used as constructors (no [[Construct]], no prototype), can't be generators, and are always expressions (not hoisted as declarations). They also have concise syntax with implicit return.
When should you not use an arrow function?
Object methods and prototype methods that use this, constructors, event handlers that rely on this being the element, generator functions, and functions that need the arguments object. In classes, arrow-valued fields are sometimes used on purpose to bind this per instance, at a memory cost per object.
What does this print?
Show solution
const makeTotal = () => { total: 0 };
const counter = { n: 1, inc: () => this?.n };
console.log(makeTotal(), counter.inc(), [1, 2, 3].map((x) => x * 2));undefined undefined [2, 4, 6]The braces in makeTotal are a block, not an object. inc is an arrow, so this isn't counter. The map callback uses an implicit return.
Practice
Challenge: Using arrow functions only, write toCents (dollars to integer cents), isLarge (true for at least 10000 cents), and a pipeline that turns [120, 85.5, 450, 99.99] into the total cents of the large amounts.
Show solution
const toCents = (dollars) => Math.round(dollars * 100);
const isLarge = (cents) => cents >= 10000;
const sum = (a, b) => a + b;
const totalLarge = [120, 85.5, 450, 99.99].map(toCents).filter(isLarge).reduce(sum, 0);
console.log(totalLarge);57000Key Takeaways
| Form | Example |
|---|---|
| Implicit return | (x) => x * 2 |
| Block body | (x) => { const y = x * 2; return y; } |
| Object return | (n) => ({ name: n }) |
| No parameters | () => Date.now() |
| Callback | arr.map((x) => x.name) |
Was this tutorial helpful?