Understanding Higher order functions in JavaScript

Aditya Dhanraj Tiwari
Code Shinobis
Published in
2 min readOct 30, 2020

Improve your code using higher order functions.

Higher order functions may sound some complicated technical term but it is nothing but a normal function which take function as arguments or return a function as their result.
JavaScript uses higher order function very heavily, it generally refer as a callback in JavaScript.

Lets understand this with code.

function square(value){
return value * value;
}
let arr = [1,2,3,4,5];
console.log(arr.map(square)) // logs: [1,4,9,16,25]

In above code function square return the square of a passed value. Here map is higher order function which takes function square as a argument.

Let’s take a look of another example.

let arr = [1,2,3,4,5];
arr.forEach(element => {
console.log(element * element);
})
//logs: 1,4,9,16,25

Here forEach is higher order function which take arrow function as a argument and apply this on all element of arrays.

Now you know what higher order functions are, now let’s take a example where using higher order function can improve your code.

In this script we have array which contains 5 names. If you see in every loop we are going through names array till particular index and performing some operation like in 1st loop converting names into uppercase, in 2nd into lowercase and in 3rd we are adding ‘Hello’ in front of every name.
So here 1 thing is common in every loop that we are performing some operation on every element of array.

Now let’s write this code using higher order functions.

Here performOperation function, which is higher order function,take number of element till you want to iterate, names array and operation to perform on each element.
operation to perform is a function which will be passed form the outside , so we have the flexibility here to perform any operation on elements of array on fly.

Creating higher order function have many benefits, If there are tricky parts of the implementation, such as getting the loop boundary conditions right, they are localized to the implementation of the higher-order function. This allows you to fix any bugs in the logic just once, instead of having to hunt for every instance of the coding pattern spread throughout your program. If you find you need to optimize the efficiency of the operation, you again only have one place where you need to change anything.

Learning higher order function will help you to keep your code concise when you are writing same code repeatedly. it also improves your code readability.

--

--