Skip to content

Beginner · Functions and closures · topic 12 of 61 · 20 min

Arrow functions

Explanation

Arrow functions are a shorter way to write function expressions: (a, b) => a + b. With a single expression after the arrow, the value is returned automatically. Arrows are ideal for small callbacks, but they do not have their own this, so do not use them as object methods that need this.

Why arrow functions?

JavaScript code passes many small functions to other functions: to sort, to filter, to react to a timer. Writing function (x) { return x * 2; } every time is noisy. Arrow functions, added in ES2015, cut this to x => x * 2.

The forms of an arrow function

javascript
const double = (n) => n * 2;            // one expression: returned automatically
const add = (a, b) => a + b;             // two parameters need brackets
const greet = () => 'Namaste';           // no parameters: empty brackets
const half = n => n / 2;                 // one parameter: brackets optional
const describe = (name, age) => {        // a body with braces needs return
  const kind = age >= 18 ? 'adult' : 'minor';
  return `${name} is an ${kind}`;
};
console.log(double(4), add(2, 3), greet(), half(9), describe('Asha', 20));
Prints 8 5 Namaste 4.5 Asha is an adult.

Implicit return and the object trap

When the body is a single expression without braces, its value is returned: this is called an implicit return. With braces, you are writing a normal block and must write return yourself.

javascript
const bad = (n) => { n * 2 };     // braces = block, no return
console.log(bad(4));              // undefined

const makeUser = (name) => ({ name, active: true }); // brackets around the object
console.log(makeUser('Ravi'));    // { name: 'Ravi', active: true }
Careful: To return an object literal from a one-line arrow, wrap it in round brackets: () => ({ id: 1 }). Without them, JavaScript reads the { as the start of a block, and the function returns undefined.

Arrows as callbacks

A callback is a function you pass to another function, which calls it later. Arrows shine here.

javascript
const prices = [499, 120, 2999];
const withGst = prices.map((p) => Math.round(p * 1.18));
console.log(withGst); // [589, 142, 3539]

setTimeout(() => console.log('Reminder: pay your bill'), 1000);

What arrows do NOT have

Arrow functions are not just shorter. They have no own this: they use the this of the code around them. They also have no arguments object, and they cannot be used with new. This makes them perfect inside methods (for callbacks) but wrong as methods themselves. Module 5 explains this fully.

javascript
const counter = {
  count: 0,
  incBad: () => { this.count++; },   // this is NOT counter here
  inc() { this.count++; },           // normal method: this is counter
};
counter.inc();
console.log(counter.count); // 1
UseArrow?Why
Small callback (map, filter, setTimeout)YesShort and uses the outer this
Object method that uses thisNoArrows have no own this
Constructor (with new)NoArrows cannot be constructors
Top-level helper functionEitherTeam style; declarations are hoisted
Think of it like this: An arrow function is like a sticky note with a quick instruction, compared with a formal letter (a function declaration). Perfect for a short message to a colleague, not for an official document that needs a letterhead (its own this).
Tip: Many teams write top-level functions with function declarations (clear names in stack traces, usable before definition) and use arrows for callbacks. Follow your team's style.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Arrow functions · 1/6

Arrow functions

In this lesson you will write arrow functions, the short way to write small functions.

Prefer a video by a teacher? Find free videos on “javascript arrow functions explained implicit return” on YouTube ↗

In real life: Sorting train results by departure

A ticket-booking app receives trains from the server and sorts them by departure time before showing them. The compare function is a one-line arrow passed to sort.

javascript
const trains = [
  { name: 'Shatabdi', departs: 615 },
  { name: 'Duronto', departs: 2330 },
  { name: 'Intercity', departs: 545 },
];
trains.sort((a, b) => a.departs - b.departs);
console.log(trains.map((t) => t.name)); // ['Intercity', 'Shatabdi', 'Duronto']

Practice (0/3 done)

Task 1 · Code · Javascript

Rewrite triple as an arrow function stored in a const named triple. It should return n * 3.

Task 2 · Code · Javascript

makeProduct should be an arrow that takes name and price and returns an object { name, price, inStock: true }. It currently returns undefined. Fix it.

Task 3 · Code · Javascript

Write sortByPrice(products) that returns a NEW array sorted by price from low to high, using an arrow compare function. Do not change the original array.

Quick quiz

Question 1

1.What does (n => { n + 1 })(5) return?

Question 2

2.Which correctly returns an object from a one-line arrow?

Question 3

3.Why is an arrow function a bad choice for an object method that uses this?

Question 4

4.Which is a valid arrow with one parameter?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What does (n => { n + 1 })(5) return?

Answer: undefined

With braces there is no implicit return, and the block has no return statement.

Which correctly returns an object from a one-line arrow?

Answer: () => ({ a: 1 })

Round brackets make the braces an object literal, not a block.

Why is an arrow function a bad choice for an object method that uses this?

Answer: Arrows have no own this

An arrow uses the this of the surrounding code, not the object.

Which is a valid arrow with one parameter?

Answer: n => n * 2

With exactly one parameter, the brackets are optional.

What does a function return if it has no return statement?Related

Answer: undefined

Without return, a function gives back undefined.

From Functions

In strict mode, function f() { return this; } What is f()?Related

Answer: undefined

A plain call in strict mode gives this = undefined.

From How this works

Does the arrow form (case X ->) fall through?Related

Answer: No

Arrow cases never fall through.

From switch statements and switch expressions

A variable declared inside a method can be used...Related

Answer: Only inside that method (its scope)

Local variables exist only inside the method that declares them.

From Methods: write once, use many times

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 3 more topics in “Functions and closures” before its exam: Parameters: defaults, rest and options objects, Scope and closures, Higher-order functions and recursion.
  2. Module 3 exam: Functions and closures · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Arrays and objects. 61 topics left in the course before the final exam.

← Previous: Functions: declarations, expressions and return