Chaining
JavaScript · Unit 10: More on functions
- Full plan
- JavaScript
- 11 exercises
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. Predict the output
What does this code print?
2. Multiple choice
What does
rhold?3. Complete the code
Fill in the blank to print what the expenses over 100 add up to.
4. Predict the output
The same steps, reversed. What does it print?
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. Find the bug
This program should add up what the items over 15 cost and print 55. Which line has the error?
7. Multiple choice
A five-step chain gives a weird result. What helps you most to find the step that fails?
8. Predict the output
The chain is already broken into steps. What does it print?
9. Complete the code
Fill in the blank to count the vowels in "education".
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. Predict the output
All together, with a named callback. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.