Understanding High-Order Array Functions In JavaScript.

Jomon
4 min readSep 27, 2020

We often come across the term High-Order function when working with Functional programming. High-Order function is nothing but a pure function that can take one or more functions as arguments or returns a function as output when invoked.

Hig-Order function

Let’s take an example to understand better.

Example #1: In the example below, a concatStr function is a higher-order function that returns a function that takes a sentence as an argument and appends the lang which is passed as an argument to the value that is being returned.

function concatStr(lang){  return function(sentence){       return `${lang} ${sentence}`  }}const progLang = concatStr('JavaScript');console.log(progLang('is a programming Language'));
//output : JavaScript is a programming language

Let’s look at some of the most used built-in high-order array functions in JavaScript.

.map()

The map() calls a provided callback function once for each element in an array and constructs a new array from the results. It takes three arguments.

Syntax : array.map(function(currentValue, index, array){});

Map() doesn’t replace the original array and it executes the element in order in which the element is defined in the array. map() doesn’t execute if the array is empty.

Lets take an example to understand the map function better

Example #2: In the example below, we have an emp object where we need to append the first name and last name and return the new appended full name. Inside our map function, we appending the first name and last name. It returns a new array with new values.

let empObj =[{firstName:’Sachin’,lastName:’T’},{firstName:’Jaison’,lastName:’M’},{firstName:’Alex’,lastName:’S’}];empObj.map(function(arr){return arr.firstName+’ ‘+arr.lastName})//output : [“Sachin T”, “Jaison M”, “Alex S”]

Let’s look at how we can achieve it using plain JavaScript function. We have to iterate through each array element and try to concatenate the firstName and LastName and push the new value to an empty array.

let empObj =[{firstName:’Sachin’,lastName:’T’},{firstName:’Jaison’,lastName:’M’},{firstName:’Alex’,lastName:’S’}];let newEmpObj =[];for(let i=0;i<empObj.length;i++){newEmpObj.push(empObj[0].firstName+’ ‘+ empObj[0].lastName)}console.log(newEmpObj);

If you look at the examples you can clearly see that you need to write more lines of code without higher-order function.

.reduce()

reduce() method execute similar like map(). reduce() executes the callback function on each member of the calling array which results in single output value. In simple, it Returns the accumulated result (from each call) from the last call of the callback function The return value is stored in the accumulator(output). It doesn’t execute the function for array elements without values. It takes four parameters — accumulator, currentValue, currentIndex, sourceArray.

The first time the callback is called, accumulator and currentValue can be one of two values. If initialValue is provided in the call to reduce(), then the accumulator will be equal to initialValue, and currentValue will be equal to the first value in the array. If no initialValue is provided, then the accumulator will be equal to the first value in the array, and currentValue will be equal to the second. If initialValue is not provided, reduce() will execute the callback function starting at index 1, skipping the first index. If initialValue is provided, it will start at index 0.

let arr = [10, 20, 30, 40, 50];
arr.reduce(function(accumulator, currentValue, currentIndex, array) {
return accumulator + currentValue});

Let’s take an example to undetand better.

Example # 3: In the example below, we have a student object where we need to sum all the marks of each subject he secured and return the new total mark.

let stud =[{subject:”English”,mark:93},{subject:”Math”,mark:65},{subject:”IT”,mark:65},{subject:”Social”,mark:89}];stud.reduce(function(acc,currVal){console.log(acc+’ ‘+currVal.mark)return Number(acc)+Number(currVal.mark)},0)

Lets set the starting value as 0. We can also use an existing variable if necessary. After running the callback for each element of the array, reduce will return the final value of our accumulator which is 312.

Without higher order reduce() function

let stud =[{subject:”English”,mark:93},{subject:”Math”,mark:65},{subject:”IT”,mark:65},{subject:”Social”,mark:89}];let total =0 ;for(let i=0;i<stud.length;i++){total = total+stud[i].mark}

As you can in Example#3 reduce() is easy to generate a single value from an object of arrays.

.filter()

Filter() creates a new array with all array element which pass the test. It doesn’t alter the original array. The callback function passed to the filter() method accepts 3 arguments: element, index, and array. The callback is invoked only for indexes of the array which have assigned values. it is not invoked for indexes that have been deleted or which have never been assigned values. Array elements that do not pass the callback test are simply skipped and are not included in the new array.

Let's take an example to understand better.

Example # 4: In the example below, we have a student object where we need to filter only the subject where the student has scored more than 70.

let stud =[{subject:”English”,mark:93},{subject:”Math”,mark:65},{subject:”IT”,mark:65},{subject:”Social”,mark:89}];stud.filter(function(currVal){ return currVal.mark>70 })

without higer-order filter() function

let highScrArr = [];let stud =[{subject:”English”,mark:93},{subject:”Math”,mark:65},{subject:”IT”,mark:65},{subject:”Social”,mark:89}];for(let i=0;i<stud.length;i++){stud[i].mark>70&& highScrArr total.push(stud[i])}

Conclusion

In short, a Higher-order function is a function that may take a function as an argument and can return a function as output. The high-order function helps us to write less code and it is easier for unit testing as well. In all the above examples, we can use the arrow function as well. I just avoid it to make it simpler for the newbies.

if you found this article helpful, please click the clap 👏button.

Happy Coding :)

--

--

Jomon

I’m a software developer and a continuous learner. #reactjs #javascript #jquery #nodejs #erp #mongo #php