JavaScript Refresh – Higher Order Functions

Size introduces complexity. Complexity confuses coders. Confused coders create bugs.

Functions help you create new vocabulary to solve problems.

Abstraction

The new vocabulary is equivalent to an abstraction. The complexities are hidden in the function.

Higher Order Functions

Higher-order functions operate on other functions or take functions as arguments.

By passing a function as an parameter, to be called in the function, we can do two completely different things in the same function.

function deleteItem (then) {
  // delete item
  then();
}

const navigateHome = () => { }

const cleanUp = () => { }

deleteItem (navigateHome);

deleteItem(cleanUp);

Higher Order Array Functions

Loop through an array.

["Ford", "Chevrolet"].forEach(car => console.log(car));

Filter items from an array.

function filter(array, test) {
  let passed = [];
  for (let element of array) {
    if (test(element)) {
      passed.push(element);
    }
  }
  return passed;
}

Transform an array with map.

function map(array, transform) {
  let mapped = [];
  for (let element of array) {
    mapped.push(transform(element));
  }
  return mapped;
}

Summarize with reduce.

function reduce(array, combine, start) {
  let current = start;
  for (let element of array) {
    current = combine(current, element);
  }
  return current;
}

console.log(reduce([1, 2, 3, 4], (a, b) => a + b, 0));
// → 10

Summary

Being able to pass function values to other functions is a deeply useful aspect of JavaScript. It allows us to write functions that model computations with “gaps” in them. The code that calls these functions can fill in the gaps by providing function values.

Arrays provide a number of useful higher-order methods. You can use forEach to loop over the elements in an array. The filter method returns a new array containing only the elements that pass the predicate function. Transforming an array by putting each element through a function is done with map. You can use reduce to combine all the elements in an array into a single value. The some method tests whether any element matches a given predicate function. And findIndex finds the position of the first element that matches a predicate.