Higher order functions~ Popular concepts ~

Higher order functions

The main building block of every application is the function. You've probably heard that the functions in JavaScript are first-class citizens. It means that we can assign a function to a variable and pass that variable to a method or return it as a result. For example:

function getProducts(fetchData) {
  return async (categoryId) => {
    const data = await fetchData({ id: categoryId });
    return data.products;
function fetchData(query) {
  return fetch(`https://site.com/api/products?id=${query.id}`);

const byCategoryId = getProducts(fetchData);
const shoes = await byCategoryId('XYZ');

Notice that fetchData is a function, and we are passing it as an argument to getProducts. Internally getProducts returns another function. We say that getProducts is a higher-order function in such cases.

We are writing higher-order functions all the time. And that is because they are the natural abstraction on top of the smaller one-job methods. We rarely want to write all the logic in one place, so we break it into smaller reusable functions. Then we need a glue code that operates with them. Very often, that glue code consists of higher-order functions.