Introduction:
In functional programming languages like Javascript functions are values that means we can pass it around like others values like string, num. We can also assign it to a variable. Confused? Don’t worry here is an example
const square = function(x){
return Math.pow(x, 2);
}
const findSquare = square;
findSquare(3); //will output 9
In the above example we have passed an anonymous function to the square variable then assign it to findSquare. Just like the above instance we can also pass function as an input to other functions. Now here Higher Order Functions comes into the picture.
Higher Order Functions:
Higher order function is the function which accepts other functions as an input. Looks complicated right? . Don’t worry it’s really simple. We will look at one of the most famous and simple higher order functions .filter(). First we will take a sample array named cars to perform the operation. And then we will first perform the filtering operation using for() loop and then .filter() to see how easy is to perform the operation with more easily readable code.
const cars = [
{mode: 'NISSAN VERSA' , type: 'SEDAN'},
{mode: 'SUBARU OUTBACK' , type: 'STATION WAGON'},
{mode: 'FORD MUSTANG' , type: 'COUPE'},
{mode: 'AUDI A4 ALLROAD' , type: 'STATION WAGON'},
{mode: 'KIA RIO' , type: 'SEDAN'},
{mode: 'AUDI A7' , type: 'HATCHBACK'},
{mode: 'TOYOTA AVALON' , type: 'SEDAN'},
{mode: 'AUDI A5' , type: 'COUPE'},
{mode: 'HONDA ACCORD' , type: 'SEDAN'},
{mode: 'KIA STINGER' , type: 'HATCHBACK'}
]
Now consider a case where we only want data related to type SEDAN. First we will see how to do this operation using for().
const SEDAN = [];
for(let i = 0 ; i < cars.length ; i++){
if(cars[i].type === 'SEDAN'){
SEDAN.push(cars[i]);
}
}
//will return [{mode: "NISSAN VERSA", type: "SEDAN"},{mode: "KIA RIO", type: "SEDAN"},{mode: "TOYOTA AVALON", type: "SEDAN"},{mode: "TOYOTA AVALON", type: "SEDAN"}]
Now let’s see using .filter() method
const SEDAN = cars.filter((car) => {
return car.type === "SEDAN"
})
The difference between both methods is not drastic but there is some difference. The code written using .filter() is more readable.Also the .fiter() does not change the original array, it returns a new array which contains the values which have satisfied the filter condition. This is an important part if you are learning React Js as states in react are immutable higher order functions like .filter() are preferred.
Advantages
- It is much easier to understand the program and the intention of the programmer is clearly expressed in the code.
- Functions which take functions as arguments are much easier to re-use than other functions.
Top comments (0)