Skip to Content
Mastering JavaScript Functional Programming - Second Edition
book

Mastering JavaScript Functional Programming - Second Edition

by Federico Kereki
January 2020
Intermediate to advanced
470 pages
11h 13m
English
Packt Publishing
Content preview from Mastering JavaScript Functional Programming - Second Edition

Calculating an average

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering JavaScript Functional Programming

Mastering JavaScript Functional Programming

Federico Kereki

Publisher Resources

ISBN: 9781839213069Supplemental Content