Higher Order Functions

Nilesh Parab
5 minute Written by Nilesh Parab on
Higher Order Functions Photo by Isabella and Louisa Fischer on Unsplash

Higher Order Function is a Functional Programming concept which is very helful in terms of reusability & readability.

:zzz: TL;DR

Higher Order Functions are simply functions that take other functions as arguments or return a function as result. A quote from Wikipedia

A higher-order function is a function that does at least one of the following:

  • takes one or more functions as arguments (i.e. procedural parameters),
  • returns a function as its result.

:pizza: Our piece

Now what it means is that, the Higher Order Function is going to provide us some additional functionality around our own function that we pass to it.

Wrapper is how I make out it & remember.

Wrapper: One who, or that which, wraps.

The most common example we see with JavaScript is the Array map function.

It takes a function that is run on each element of the array to return a new array. Let’s break it down:

  • It iterates on each element of array
  • It executes the function passed on argument on each element
  • It returns a new array

:computer: Some actuals

Consider an example, we have an array of numbers & we want to find square of each of them.

// create array of numbers
const numbers = [ 2, 3, 4, 5 ];
// Function that takes a number & 
// returns result that is the product of number with itself (square)
const square = (num) => num * num;
// new array created using map function, 
// that uses square function on each element in numbers array
const squared_numbers = numbers.map(aNumber => square(aNumber));
// printing the input & output arrays
console.log('Numbers: ', numbers);
console.log('Squared Numbers: ', squared_numbers);

Here is the output when we run it in browser console:

image

Some few more examples of Higher Order Functions too that we use daily but fail to notice them:

  • filter
  • reduce
  • some

Similar concept is leveraged by React for Higher Order Components which I will cover in another article.

Nilesh Parab
About Nilesh Parab I love building things using Java & JavaScript. Professionally I am more focussed in eCommerce. Music. Motorcycling.