Summary - Arrow functions
- JavaScript course
- Intermediate
- Lesson 6/134
- 5 min
Build an array filtering and sorting tool using arrow functions.
Summary - Arrow functions
In this group you learned arrow functions: the => arrow, concise and block bodies, parameter usage, lexical this, and that arrows cannot be constructors. Now you will combine them in a small tool.
Goal: a tool that filters a product array by price, sorts it, and computes the total. Every function will be an arrow.
Practice Filter and sort by price
Write a filterByPrice arrow function. It takes a maxPrice parameter. From the products array, use filter to keep items whose price is less than or equal to maxPrice, then sort them by price ascending. Use arrow callbacks in both.
Starter code
const products = [
{ name: "pen", price: 25 },
{ name: "notebook", price: 40 },
{ name: "eraser", price: 10 }
];
const filterByPrice = (maxPrice) => {
// write here
};Sample solution
const filterByPrice = (maxPrice) => {
return products
.filter((p) => p.price <= maxPrice)
.sort((a, b) => a.price - b.price);
};Practice Compute the total price
Write a totalPrice arrow function. It takes an items parameter and returns the sum of all product prices using reduce. The initial value should be 0.
Starter code
const totalPrice = (items) => {
// write here
};Sample solution
const totalPrice = (items) =>
items.reduce((sum, item) => sum + item.price, 0);Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is true?
- An arrow function can be called with new
- A block body does not use return
- An arrow has its own arguments object
- With one parameter, parentheses are optional Correct answer
Explanation: With one parameter, parentheses can be dropped: <code>n => n + 1</code>.
2 Match the concepts
| Term | Meaning |
|---|---|
=> arrow |
arrow function |
lexical this |
inherits outer scope |
...args |
rest parameter |
new arrow |
throws TypeError |
3 What is the result?
[5, 10, 15].reduce((a, b) => a + b, 0);- 30 Correct answer
- 25
- 15
- 0
Explanation: answer 30. reduce starts at 0 and adds every element.