Arrow Functions
Modern JavaScript is full of small functions passed to other functions: "double each price", "keep only the paid orders", "run this when the button is clicked". Writing function (x) { return ... } every time is long. Arrow functions are a shorter way to write functions, named after the => arrow in their syntax.
In this lesson you will learn the arrow function syntax in all its forms, the one trap with returning objects, and the important ways arrow functions behave differently from normal functions.
From function to arrow
Here is the same function written twice, first as a function expression and then as an arrow function:
const double1 = function (n) {
return n * 2;
};
const double2 = (n) => n * 2;
console.log(double1(21));
console.log(double2(21));42 42
To get from the first to the second: remove the word function, put => after the parameters, and, because the body is a single expression, drop the braces and the word return. The arrow function gives back the value of that expression automatically. This is called an implicit return.
The forms of arrow functions
const sayHi = () => "Hi!";
const square = (n) => n * n;
const add = (a, b) => a + b;
const bmi = (weightKg, heightM) => {
const value = weightKg / heightM ** 2;
return value.toFixed(1);
};
console.log(sayHi());
console.log(square(9));
console.log(add(2, 3));
console.log(bmi(68, 1.72));Hi! 81 5 23.0
| Situation | Write |
|---|---|
| No parameters | () => ... (empty brackets are required) |
| One parameter | (n) => ... or n => ... |
| Several parameters | (a, b) => ... |
| One expression | (a, b) => a + b, returned automatically |
| Several statements | (a, b) => { ...; return result; } |
With exactly one parameter, the brackets are optional. Many teams and code formatters always write them, (n) =>, so adding a second parameter later is easier. This tutorial does the same.
Braces mean you need return
As soon as you add curly braces, the arrow function becomes a normal block, and you must write return yourself. Forgetting it is the most common arrow function bug:
const total1 = (a, b) => a + b;
const total2 = (a, b) => { a + b; };
const total3 = (a, b) => { return a + b; };
console.log(total1(200, 50));
console.log(total2(200, 50));
console.log(total3(200, 50));250 undefined 250
total2 calculates a + b and throws the result away, so it returns undefined.
Returning an object
Curly braces after => always mean a block of code, never an object. To return an object with an implicit return, wrap it in round brackets:
const makeBooking = (passenger, seat) => ({ passenger: passenger, seat: seat });
const booking = makeBooking("Kabir", "B2-34");
console.log(booking.passenger);
console.log(booking.seat);Kabir B2-34
Without the round brackets, (passenger, seat) => { passenger: passenger } is read as a code block, the function returns undefined, and booking.seat would throw an error. You will learn object syntax in Objects.
Arrow functions as callbacks
Arrow functions shine when you pass a function to another function, which is called a callback. Array methods are the most common place:
const prices = [499, 1299, 89];
const doubled = prices.map((price) => price * 2);
const cheap = prices.filter((price) => price < 500);
console.log(doubled);
console.log(cheap);[ 998, 2598, 178 ] [ 499, 89 ]
map() calls the arrow function once for each price and collects the results; filter() keeps the prices for which the arrow returns true. The arrow syntax keeps each line short enough to read at a glance. You will learn these methods in Array Methods and the idea of callbacks in Callbacks & Higher-Order Functions. Event handlers often use arrows too: button.addEventListener("click", () => { ... }).
How arrow functions are different
Arrow functions are not just shorter; they also behave differently in three ways:
- No own
this. An arrow function uses thethisof the code around it. That is helpful inside methods and callbacks, but it means an arrow function is a poor choice for an object's own method. - No
argumentsobject. Use rest parameters (...args) instead, which is better anyway. - Cannot be used with
new. Arrow functions cannot create objects as constructors; use a class instead.
The first difference matters most. In the example below, greet is a normal method, so this is the shop object. The arrow version does not get its own this, so it does not see the shop at all:
const shop = {
name: "Kabir Mobiles",
greet() {
return `Welcome to ${this.name}`; // this is shop
},
greetArrow: () => `Welcome to ${this.name}`, // this is NOT shop
};You will learn exactly how this works in The this Keyword, and classes in Classes.
Also remember that an arrow function stored in a const is an expression, so, unlike a function declaration, you cannot call it on a line above where it is defined.
When to use which
- Callbacks and short helpers: arrow functions.
- Named, top-level functions such as
calculateEmi(): either style is fine. Many teams preferfunctiondeclarations here, because the name is easy to spot and they can be called from anywhere in the file. - Methods in objects and classes that use
this: the method shorthandgreet() { ... }, not an arrow.
Common mistakes
- Braces without
return.(x) => { x * 2 }returnsundefined. Remove the braces or addreturn. - Returning an object without brackets. Write
() => ({ ok: true }), not() => { ok: true }. - Arrow functions as object methods. They do not get the object as
this. Use the method shorthand. - Forgetting the empty brackets. A function with no parameters still needs
() =>.
Key points
(params) => expressionis a short function that returns the expression automatically.- With curly braces, the body is a block and you must write
return. - Wrap an object in round brackets to return it:
() => ({ ... }). - Arrow functions are ideal for callbacks like
map(),filter()and event handlers. - They have no own
this, noargumentsand cannot be used withnew.
Exercise
Rewrite these three functions as arrow functions, using implicit returns where possible. Then call each one and print the result.
function toPaise(rupees) {
return rupees * 100;
}
function isWeekend(dayNumber) {
return dayNumber === 0 || dayNumber === 6;
}
function fullName(first, last) {
const name = first + " " + last;
return name.toUpperCase();
}Show solution
const toPaise = (rupees) => rupees * 100;
const isWeekend = (dayNumber) => dayNumber === 0 || dayNumber === 6;
const fullName = (first, last) => `${first} ${last}`.toUpperCase();
console.log(toPaise(45));
console.log(isWeekend(6));
console.log(fullName("Priya", "Nair"));4500 true PRIYA NAIR
Each function is a single expression, so none of them needs braces or return. The template literal builds the name, and toUpperCase() is called on the result.
Quick Quiz
1. What does const f = (x) => { x + 1; }; f(5) return?
With curly braces the body is a block, and there is no return, so the result is undefined.
2. Which arrow function correctly returns an object?
Round brackets around the object tell JavaScript it is a value, not a code block.
3. Which statement about arrow functions is true?
Arrow functions do not create their own this, which is why they suit callbacks but not object methods.
Learn JavaScript with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
