Arrow Functions

JavaScript · Lesson 17 of 61 6 min read Updated

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:

JavaScriptRun it yourself
const double1 = function (n) {
  return n * 2;
};

const double2 = (n) => n * 2;

console.log(double1(21));
console.log(double2(21));
Output
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

JavaScriptRun it yourself
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));
Output
Hi!
81
5
23.0
SituationWrite
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:

JavaScriptRun it yourself
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));
Output
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:

JavaScriptRun it yourself
const makeBooking = (passenger, seat) => ({ passenger: passenger, seat: seat });
const booking = makeBooking("Kabir", "B2-34");

console.log(booking.passenger);
console.log(booking.seat);
Output
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:

JavaScriptRun it yourself
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);
Output
[ 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 the this of 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 arguments object. 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:

JavaScript
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 prefer function declarations 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 shorthand greet() { ... }, not an arrow.

Common mistakes

  • Braces without return. (x) => { x * 2 } returns undefined. Remove the braces or add return.
  • 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) => expression is 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, no arguments and cannot be used with new.

Exercise

Rewrite these three functions as arrow functions, using implicit returns where possible. Then call each one and print the result.

JavaScript
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
JavaScript
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"));
Output
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?

2. Which arrow function correctly returns an object?

3. Which statement about arrow functions is true?

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