WTF is higher-order functions?

WTF is higher-order functions?

Table of contents

Hi there, I am Shivam, and here's my explanation of higher-order functions in Javascript.

Definition

In Javascript, a higher-order function is a function that takes another function as an argument and returns a function as a result. For example, look at the following code:

const products = [
  { name: 'Apple', price: 1.99, category: 'fruit' },
  { name: 'Banana', price: 0.99, category: 'fruit' },
  { name: 'Carrot', price: 0.49, category: 'vegetable' },
  { name: 'Broccoli', price: 0.89, category: 'vegetable' },
  { name: 'Steak', price: 9.99, category: 'meat' },
  { name: 'Chicken', price: 5.99, category: 'meat' }
];

function filterBy(prop, value) {
  return function(item) {
    return item[prop] === value;
  }
}

const fruitFilter = filterBy('category', 'fruit');

const filteredProducts = products.filter(fruitFilter);

console.log(filteredProducts); 
// logs
// [{ name: 'Apple', price: 1.99, category: 'fruit' }]
// [{ name: 'Banana', price: 0.99, category: 'fruit'}]

In this example, we define an array of products with properties name, price, and category. We then define a filterBy function that takes a prop argument and a value argument, and returns a closure that filters an array of objects by that prop and value.

We then create a function, fruitFilter , by calling filterBy with the arguments 'category' and 'fruit'. This function is a closure that remembers the prop and value arguments passed to filterBy.

We can then use this filter function with the filter method on the products array to get a new array that only contains products that match the filter criteria:

const filteredProducts = products.filter(fruitFilter);

This returns an array containing only the Apple and Banana product objects, because those are the only ones that match the 'category' of 'fruit'.

This example shows how higher-order functions can be used with closure and currying to create reusable and composable functions that can perform complex operations on data.

I'm grateful for your interest in my work and for taking the time to engage with my content. Thank you for being an awesome reader!

Want to talk? More at shivamsharma.net.

bye✌️.