Member-only story

Higher-order functions .map, .filter and .reduce in JavaScript

Ghost Together

--

Things I want to accomplish in this Higher Order Function tutorial:

  1. Introduce newbies to the idea of Higher Order Function in JavaScript.
  2. (In a way that entertains, because HOs can get quite boring.)
  3. Show fun animations explaining how Higher Order functions work.

JavaScript Grammar book explains higher-order functions in detail and also shows you how they work by creating your own version of .map() method. (Among many other great examples.)

Array.map — map all values to an expression.

To kick off this tutorial I’ll start with animated example of higher-order function map. It modifies each item in the original array and returns a copy. In this case we’re simply incrementing all array items by 1. Or in other words it “maps” a new value to existing items by following the supplied expression.

**Array.map(): apply “value + 1” to a set of 7 numbers [1, 2, 3, 4, 5, 6, 7]**

1] Expression ```value + 1``` is applied to every item in the original array.
2] .map()``` returns a modified copy of the array leaving original untouched.
3] Result: ```[2,3,4,5,6,7,8]``` (a copy of the original array is created.)

The higher order function map can be used for mapping items in one format to another. (Number to String, for example.)

Like any other higher-order function map can be applied to many different problems. It depends on what you’re trying to do with a given dataset.

Higher-order functions are abstract on purpose. They are not here to tell you exactly what problems you should be solving using them. They simply capture a commonplace pattern present in many basic logical problems.

Array.filter — keep all that match a condition.

--

--

Responses (1)