Categories
Javascript

How to use Higher order functions in JavaScript

Let’s delve into the realm of higher order functions and experience a new world of possibilities together !!

Improve your code readability 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]

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, A higher order function takes arrow function as a argument and apply this on all element of arrays.

Now you know what higher order functions are.

Let’s take an 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 three aargument n, array and callback.
operation to perform is a function which will be passed form the outside, which gives us flexibility to perform any action.

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 need to change code, 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.

Hope you have enjoyed the article. Good luck and Happy Coding.

Let the author know what's in your mind !!

This site uses Akismet to reduce spam. Learn how your comment data is processed.