Beginner · Functions and closures · topic 12 of 61 · 20 min
Arrow functions
Explanation
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
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));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.
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 }Arrows as callbacks
A callback is a function you pass to another function, which calls it later. Arrows shine here.
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.
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| Use | Arrow? | Why |
|---|---|---|
| Small callback (map, filter, setTimeout) | Yes | Short and uses the outer this |
| Object method that uses this | No | Arrows have no own this |
| Constructor (with new) | No | Arrows cannot be constructors |
| Top-level helper function | Either | Team style; declarations are hoisted |
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
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.
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)
Rewrite triple as an arrow function stored in a const named triple. It should return n * 3.
makeProduct should be an arrow that takes name and price and returns an object { name, price, inStock: true }. It currently returns undefined. Fix it.
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Parameters: defaults, rest and options objectsFunctions and closures · same module
- Scope and closuresFunctions and closures · same module
- FunctionsFrontend Web Development · JavaScript basics
- How this worksScope, this, prototypes and classes
- switch statements and switch expressionsJava Programming (Core to Spring Boot) · Control flow and methods
- Methods: write once, use many timesC# and .NET · Decisions, loops and methods
Questions people ask about this
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
In strict mode, function f() { return this; } What is f()?Related
Does the arrow form (case X ->) fall through?Related
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.
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
- 3 more topics in “Functions and closures” before its exam: Parameters: defaults, rest and options objects, Scope and closures, Higher-order functions and recursion.
- Module 3 exam: Functions and closures · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Arrays and objects. 61 topics left in the course before the final exam.