Functional Programming
JavaScript is not a functional programming language like Lisp or
Haskell, but the fact that JavaScript can manipulate functions as
objects means that we can use functional programming techniques in
JavaScript. The ECMAScript 5 array methods such as map() and reduce() lend themselves particularly well
to a functional programming style. The sections that follow
demonstrate techniques for functional programming in JavaScript. They
are intended as a mind-expanding exploration of the power of
JavaScript’s functions, not as a prescription for good programming
style.[14]
Processing Arrays with Functions
Suppose we have an array of numbers and we want to compute the mean and standard deviation of those values. We might do that in nonfunctional style like this:
vardata=[1,1,3,5,5];// This is our array of numbers// The mean is the sum of the elements divided by the number of elementsvartotal=0;for(vari=0;i<data.length;i++)total+=data[i];varmean=total/data.length;// The mean of our data is 3// To compute the standard deviation, we first sum the squares of// the deviation of each element from the mean.total=0;for(vari=0;i<data.length;i++){vardeviation=data[i]-mean;total+=deviation*deviation;}varstddev=Math.sqrt(total/(data.length-1));// The standard deviation is 2
We can perform these same computations in concise functional
style using the array methods map() and reduce() like this (see ECMAScript 5 Array Methods to ...
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.
Read now
Unlock full access