Higher Order Functions in JavaScript Explained Simply

Navigating through JavaScript, you might stumble upon a concept called "higher-order functions."

Graphic illustration showing higher-order functions in JavaScript with a large function symbol surrounding smaller ones, arrows illustrating function flow, against a background of code patterns and JavaScript terms.

This term might sound complex, but I'm here to simplify it and surprise you by showing you how you might already be familiar with it.

What is a Higher Order Function?

Let's not overcomplicate this.

A higher-order function is essentially a function that does something with other functions.

It's a function that can accept functions as a parameter, return a function, or do both.

Why Should I Use Them?

Why bother with higher-order functions?

If you've used JavaScript array operations, like forEach, map, filter, or reduce (to name a few), you've already used them!

As you can see, by using these handy abstracting actions, they minimize repetition and clutter.

If you haven't, I'll run through a little example to make sure you have the foundational knowledge so you can see it in action before creating your own.

A (Hopefully) Familiar Example

Consider an array of prices that need to be adjusted for a sale.

First let's look at how we would do this without a Higher Order Function:

const prices = [10, 20, 30, 40];

function getSalePrices(array) {
    let newPrices = [];
    for (let i = 0; i < array.length; i++) {
        newPrices.push(array[i] * 0.9);
    }
   return newPrices;
}

const salePrices = getSalePrices(prices);
console.log(salePrices);  // Output: [9, 18, 27, 36]

Here's here's how map simplifies this:

const prices = [10, 20, 30, 40];

const salePrices = prices.map(price => price * 0.9); // 10% off
console.log(salePrices); // Output: [9, 18, 27, 36]

Map takes a function (which means it is a "Higher Order Function") and applies our logic, which helps us encapsulate a lot of the complexity, as seen by our example without a map function.

Returning a Function Example

As I said earlier, a Higher Order Function can return a function.

To make sure you understand what this looks like, let's create some discount functions:

function discount(discountRate) {
  return function(price) {
    return price - (price * discountRate);
  }
}

const tenPercentOff = discount(0.1);
/*
tenPercentOff equals: 
function(price) {
  return price - (price * 0.1);
}
*/

const twentyPercentOff = discount(0.2);
/*
twentyPercentOff equals: 
function(price) {
  return price - (price * 0.2);
}
*/

console.log(tenPercentOff(100)); // Output: 90
console.log(twentyPercentOff(100)); // Output: 80

Pretty handy, right?

## Another Custom Example

We already created our first custom Higher Order Function in the previous example but let's create a

Let's create a higher-order function that keeps with the theme of applying discounts, but this time, it will take a function as a parameter.

This approach allows for even more flexibility, as you can pass different discount functions based on your criteria (like customer type, promotional events, etc.).

function applyDiscount(total, discountFunction) {
  return discountFunction(total);
}

// Discount functions
function regularCustomerDiscount(total) {
  return total * 0.9; // 10% discount
}

function vipCustomerDiscount(total) {
  return total * 0.8; // 20% discount
}

// Applying different discounts
const regularCustomerTotal = applyDiscount(100, regularCustomerDiscount);
console.log(`Regular Customer Total: $${regularCustomerTotal}`); // Output: Regular Customer Total: $90

const vipCustomerTotal = applyDiscount(100, vipCustomerDiscount);
console.log(`VIP Customer Total: $${vipCustomerTotal}`); // Output: VIP Customer Total: $80

This example demonstrates the power of higher-order functions in creating flexible and reusable code structures.

By passing functions as parameters, you can dynamically change the behavior of your code without directly modifying its structure.


Now you can sleep safely knowing that you'll always know that a Higher Order Function is just a function that plays with other functions.

Using higher-order functions helps web developers break their code down into easier bits. It's like keeping things tidy and simple, which makes finding and fixing bugs a lot less of a headache.

Happy coding! ✨

JavaScriptJS
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.