Higher Order Function
Before Higher order function we have to know about function. So let us introduce a function.
What is a function?
A function is a block of code that can solve a particular task and give result. A function must have a name and body. And also can have argument if needed by which it works and prepare output.
Functions are executed when they are called by name.
Example:
function Add(A,B) {
return A+B;
}
Now What is Higher order function?
Higher order function is a function that can receive another function as argument and return a function as output.
Sometimes we need to do some task in a function and one of the task is already done in another function which is created. At that moment to reduce code or complexity we can use this function as argument or return value.
Example:
Output: hello hamidur
here, hello() is a higher order function which take print() function as it’s argument. and return value from print() function.
Here we can see that filterEven is a function that filter all even numbers from an array. To find even numbers it use another function named test as it’s argument.
Filtering Array:
Array can be filtered it’s component on condition using filter() method. Filter() is a method of array that used to filter an array.
The filter array method creates a new array with all elements that pass the test implemented by the provided function.
Suppose we want to filter an array to even numbers. To find the even number it declare a function findEven(). And finally it find the even numbers by calling filter() method with argument findEven().
Example:
We can also write the function in this way… output will be same.
Output: 2,4,6,8
Summarizing with Reduce:
The reduce() method applies to a function against an accumulator to find a single value from an array based on condition.
Reduce() method provide a loop for the array and execute the function for each value of the array. The Return value is stored in the accumulator.
Example: Suppose we want to find the maximum value from an array . To solve this problem a function findMax() is used . In this function val is the accumulator which store the result. And maximum value is found by calling reduce() method with findMax() method.
Here the output is 9.
Another example is here, the reduce method is used to find the sum of all values in the array.
Transform with map:
map() is an array method to update the old array values. It calls with a function and create a new array with the result of calling function which works for every element of the array.
Example: Suppose we want to update an array for any reason . we want that every element of the array will be update by increasing 2.
Output: 3,4,5,6,7
We can also create a mapped function. In the example bellow we convert every element of the array into uppercase.
Output: A,B,C