Skip to the content

Chaining

JavaScript · Unit 10: More on functions

Since filter and map return an array, you can chain them, and reduce can close the chain. You read it top to bottom: each step gets what the previous one left.

reduce returns a single value, so it goes last.

const prices = [120, 45, 300, 80];
const total = prices
  .filter((p) => p >= 80)
  .map((p) => p - 10)
  .reduce((t, p) => t + p, 0);
console.log(total);

Prints

470

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Multiple choice

    What does r hold?

  3. 3. Complete the code

    Fill in the blank to print what the expenses over 100 add up to.

  4. 4. Predict the output

    The same steps, reversed. What does it print?

  5. 5. Put the lines in order

    Put in order the function that adds up what you pay for the products over 100, with a coupon that takes 20 off each one.

  6. 6. Find the bug

    This program should add up what the items over 15 cost and print 55. Which line has the error?

  7. 7. Multiple choice

    A five-step chain gives a weird result. What helps you most to find the step that fails?

  8. 8. Predict the output

    The chain is already broken into steps. What does it print?

  9. 9. Complete the code

    Fill in the blank to count the vowels in "education".

  10. 10. Find the case that fails

    initials(name) should return the initials in uppercase, like "AS" for "ann stone", even if there are extra spaces between the words. Which call does it fail with?

  11. 11. Predict the output

    All together, with a named callback. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →