CodeBlanks Logo Icon CodeBlanks

Summary - Arrow functions

JavaScript course · Intermediate · Lesson 6/134

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.

Exercise 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.

Show example solution
const filterByPrice = (maxPrice) => {
  return products
    .filter((p) => p.price <= maxPrice)
    .sort((a, b) => a.price - b.price);
};

Exercise 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.

Show example solution
const totalPrice = (items) =>
  items.reduce((sum, item) => sum + item.price, 0);

Test yourself

  1. Which is true?

    • An arrow function can be called with new
    • With one parameter, parentheses are optional
    • An arrow has its own arguments object
    • A block body does not use return
    Show answer

    With one parameter, parentheses are optional — Correct. With one parameter, parentheses can be dropped: <code>n => n + 1</code>.

  2. Match the concepts

    => 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);
    • 15
    • 25
    • 30
    • 0
    Show answer

    30 — Correct. 0 + 5 + 10 + 15 = 30.

All lessons in Intermediate