Higher Order Function
How to Pass a Function as an Argument to Another Function
In this section, we will see how we can send a function as an argument and ultimately how it helps us write cleaner code.
Consider the following code in which we want to create a function that accepts an array as an argument. It filters out all the odd numbers from it and returns all the filtered numbers.
The function will look something like this:
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
function filterodd(){
const filterArr =[];
for(let i=0 ;i<arr.length; i++){
if(arr[i] % 2 !==0){
filteredArr.push(arr[i]);
}
}
return filterArr;
}
console.log(filtereodd(arr));
But notice that we are writing a lot of duplicate code in this approach. Both the above functions do a lot of common things, like accepting the original array, creating a new array to store the filtered array, looping through the whole main array, and finally returning the filtered array.
Let's make the function which does all the common stuff we performed in the filterOdd
functions. This will go something like this:
function filterFunction(arr, callback) {
const filteredArr = [];
for (let i = 0; i < arr.length; i++) {
callback(arr[i]) ? filteredArr.push(arr[i]) : null;
}
return filteredArr;
}
Ignore the callback
parameter for now. Notice how in the new filterFuntion
we kept all the common steps, that is accepting the original array, creating a new array to store the filtered array, looping through the whole main array, and finally returning the filtered array that we were performing in the filterOdd
functions.
Now the callback
parameter basically accepts the logic which will be nothing but another function containing the filtering logic. For filtering the odd numbers, respectively, here are the logic functions we need to write:
// Function containing logic for filtering out odd numbers
function isOdd(x) {
return x % 2 != 0;
}
// Function containing logic for filtering out even numbers
function isEven(x) {
return x % 2 === 0;
}
That's it! We now just need to pass the main array, along with the logic function to our filterFunction
like this:
// For filtering out odd numbers
filterFunction(arr, isOdd)
// Output of console.log(filterFunction(arr, isOdd)):
// [ 1, 3, 5, 7, 9, 11 ]
// For filtering out even numbers
filterFunction(arr, isEven)
// Output of console.log(filterFunction(arr, isEven)):
// [ 2, 4, 6, 8, 10 ]