January 2020
Intermediate to advanced
470 pages
11h 13m
English
Let's work a bit more. How do you calculate the average of a list of numbers? If you were explaining this to someone, your answer would surely be something like sum all the elements in the list and divide that by the number of elements. This, in programming terms, is not a procedural description (you don't explain how to sum elements, or how to traverse the array), but rather a declarative one, since you say what to do, not how to do it.
We can transform that description of the calculation into an almost self-explanatory function:
const average = arr => arr.reduce(sum, 0) / arr.length;console.log(average(myArray)); // 27.166667
The definition of average() follows what would be a verbal explanation: sum the elements ...