DevPath · Learn to code ESPTEN

Functional programming

Higher-order functions and map/filter/reduce

Higher-order functions

A higher-order function is one that receives a function as an argument or returns a function. In JavaScript, functions are "first-class values": they can be passed and returned like any other data.

The three pillars of functional programming with arrays are higher-order functions:

map: transform each element

const numbers = [1, 2, 3];
const doubles = numbers.map((n) => n * 2); // [2, 4, 6]

filter: keep some of them

const evens = numbers.filter((n) => n % 2 === 0); // [2]

reduce: combine everything into one value

const sum = numbers.reduce((accumulated, n) => accumulated + n, 0); // 6

reduce receives an accumulator and each element, and returns the new accumulator. The second argument (0) is the initial value. It is the most powerful one: with reduce you can express both map and filter.

These functions do not mutate the original array: they return a new one, which fits with immutability.

Examples

Chain map, filter and reduce

const numbers = [1, 2, 3, 4, 5, 6];
const result = numbers
  .filter((n) => n % 2 === 0) // [2, 4, 6]
  .map((n) => n * n)          // [4, 16, 36]
  .reduce((a, n) => a + n, 0); // 56
console.log(result);
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Pure functions and immutabilityComposition and currying →