Higher-Order Functions in JavaScript.
By: Justine Peterson Mahinyila
Tags: Javascript Tips, Functions In Javascript, Array Methods, Arrays, Closure

A function is a block of code that can be executed to perform a certain action, In Javascript, we have an anonymous function which as its name suggests it is anonymous(Does not have a name) and a normal function that contains a name that can be used to call the function for it to execute but that is another story for another day since this is a note about higher-order functions we will now focus on Higher-order functions.

A higher-order function is a function that has multi-levels ie. it can take another function as an input or it can give back a function as an output. In any modern codebase, you are likely to encounter these functions therefore it is important to understand them.

Let’s take the example of the Javascript Array object which has a lot of higher-order functions which some of them like sort, map, reduce, and filter we will cover these here, but before that let’s go through few javascript concepts that are very important for our understanding of the Higher-order functions later.

A Callback

A callback is a function that gets called after another function has been called. A good analogy example is an event call functions after a button has been placed.

function multiplier(factor){

return function(x){

return x * factor;

}

}

The multiplier function when called returns another function(a callback an anonymous function which receives an argument x. The above function is also called a closure since.

Arrow functions vs Noraml functions

Arrow functions are functions that were introduced on ES6 which allows us to write code in a very short and concise way compared to Normal functions.

*Normal Function

function (x){

return x * x;

}

The above function can be written as an arrow function as follows,

*Arrow Function.

x => x*x;

This is very concise since we only do have a single line of code, no keyword, no-curl brackets, and no brackets before the parameter x. This function when executed will return the same result as if it were written as the normal function

Array concerning a higher-order function.

An Array is a list of items(numbers, strings, objects, or even other arrays) that you can iterate through it.

Higher-order functions help you to manipulate an array as a whole

Now that we have those concepts out of the way let’s go through some of the Higher-order array functions:-

Map

A map allows you to pass a function that applies to every element of an Array that is why we call it a higher-order function.

//Let us create an array vals that contins numbers

let vals = [1,3,4,5]; //Now we create a function called doubler that accepts an argument //nand multply it by two(it doubles it) function doubler(x){

return x * 2;

} //next we are going to call a function map on vals and pass a the //function double as its argument

vals.map(double); console.log(vals);// observe that the array vals remains unchanged //now let us create a varibale called doubled that will receive the //output of the map fucntion called on the array vals.

let doubled = vals.map(doubler) console.log(doubled);//observe the array elements

As we can observe in the above example the map function does not alter the original array but uses the original array to create a new array that is acted upon by the functions passed on the map argument function.

Fill

One of the differences between fill as a map is that fill acts on the actual original array, it does not create a new array as it is to map. It allows you to fill items to an array from a specified position to a certain position

syntax ;

array.fill(value, start, end)

Value is the value you want to fill in n array, the start is optional is the index to start filling the array (default is 0), the end is also optional is the index to stop filling the array (default is array.length)

/*

here we are going to call the fill function on our array vals which means that we are going to fill/replace all the elements in the vals array with zero(the argument we have passed on fill) then we are going to call the map function which we expect it to replace each elemet(which is now zero due to the effect of fill) to a new random number (due to the Math.random we have passed on the map function as an argument)

*/

vals.fill(0).map(Math.random);

console.log(vals)

/*you will see that all the values of vals have changed to zeros and no random number in it does it mean the map function did not take effect ? No, do you remember the difference between fill and map? then that is what happened, the fill function acted on the actual array while the map function used the elements of vals but never changed them

*/ let randomised = vals.fill(0).map(Math.random)

console.log(randomised)

//now we have the effect we were looking for.

Reduce

The Reduce function takes two arguments, the first on is a function that contains two parameters the accumulator and the current value, and the second one is an initial value(if left blank the reduce function will take the first element of an array as the initial value), As its name suggests a reduce function will only return one value and only one value.

Let’s say we wanted to add all the elements of an array and obtain a total value. In a normal way, we could do something like this.

let vals = [1,4,5,6,2,9]; let sum = 0; for(let val of vals ){

sum + = vals;

} console.log(sum);

Using reduce this could be reduced to something like this

function sum(acc,val){

return acc + val;

} let answer = vals.reduce(sum); console.log(answer);

Filter

FIler is a higher-order function that expects as an argument a function, it can filter out some array elements.

The function passed in as an argument can either return false or truthy. Which will determine the elements to be filtered out. Also, the filter does not act on the actual array.

let vals = [1,2,3,5,6]; function isEven(num){

if(num%2 == 0){

return num;

}

} let even = vals.filter(num=>isEven(num)); console.log(even)

//this will return all the even numbers

Sort

The sort function can be used to arrange elements in ascending or descending order for example it can be used to put a word “apple” before “banana” since alphabetically a appears before b. Sort can be misleading numerically for it will positon 40 before 100 since 4 is greater than 1 which makes it important to use compare function for correctness.

Syntax:-

array.sort(compareFunction)

A compare function is an option that redefines the sort order by accepting two arguments and returning a positive or negative value which determines how to arrange the two values.

let vals = [1,4,5,2,56,8,9]; const compare = (a,b)=>{

return a - b;

} console.log(vals.sort((a,b)=>compare(a,b)));

wow, we have reached the end of our notes, please do not hesitate to leave a comment on suggestion or corrections to these notes.