I am online
← Back to Articles

Higher Order Functions in JavaScript

JavaScriptJune 7, 2024

Introduction

Higher-order functions are functions that work with other functions. They either accept functions as arguments or return functions as results.

You probably use them frequently, often without realizing it. Higher-order functions help write concise, minimal, and functional-style code by abstracting repetitive logic into testable functions.

Consider this simple data structure:

const cart = [
  { name: "Solar panel", price: 299 },
  { name: "Solar inverter", price: 399 },
  { name: "Battery", price: 199 },
];

Functions as Arguments

Let's use Array.prototype.reduce to calculate the total price of items in the cart:

const total = cart.reduce((prev, next) => prev + next.price, 0);
console.log(total); // 897

Functions that Return Functions

Now, let's create a higher-order function that applies a discount to items before adding them to the cart.

First, the basic add to cart function:

function addToCart(item) {
  cart.push(item);
}

Next, a function that returns another function to apply a discount:

function addToCartWithDiscount(amount) {
  return function (item) {
    const price = item.price * amount;
    addToCart({ ...item, price });
  };
}

We can create reusable functions for different discount amounts:

const addToCartWith20Discount = addToCartWithDiscount(0.8); // 20% discount
const addToCartWith40Discount = addToCartWithDiscount(0.6); // 40% discount
const addToCartWith60Discount = addToCartWithDiscount(0.4); // 60% discount
const addToCartWith80Discount = addToCartWithDiscount(0.2); // 80% discount

Using these functions is straightforward:

const item = { name: "Solar panel", price: 299 };
addToCartWith40Discount(item); // Applies 40% discount

console.log(cart); // [{ name: 'Solar panel', price: 179.4 }]

Higher-order functions make code cleaner, easier to test, and more flexible. They are a key concept in functional programming, closely related to closures, which provide powerful tools for composition and abstraction.