DevelopmentJavaScript | 3 Min Read
JavaScript Fundamentals: Higher Order Functions
When looking into functons within JavaScript, a term that is likely to come up is Higher Order Functions, here's all you need to know about them.
- Functions that return other functions or take other functions as arguments.
- Taking another function as an argument is referred to as a callback function as it is being called back by the higher-order function
For example, the map function
1[1, 2, 3, 4].map((num) => num * num); // [1, 4, 9, 16]
jsxOther Examples include forEach, reduce, filter and sort.
If we didn't have the map higher-order function and had to use normal functions it would look like:
1const base = [1, 2, 3, 4];2const result = [];3
4for (let i = 0; i < base.length; i++) {5 result[i] = base[i] * base[i];6}7
8console.log(result); // [1, 4, 9, 16]
jsxBy using the map higher-order funciton we have to write less code which not only reduces the risks of introducing errors but also makes the code more readable.
Building the puzzle pieces
One of the biggest benefits of using higher-order functions is the ability to mix and match them together. For example, if we wanted to answer the following questions about the below dataset we can write one function that handles one piece of logic and reuse it.
Questions
- Average of everyone's age
- Average age of each sex.
- Oldest of each sex
1const people = [2 { name: "Coner", age: 21, sex: "M" },3 { name: "Sandra", age: 40, sex: "F" },4 { name: "Jon", age: 60, sex: "M" },5 { name: "Emily", age: 16, sex: "F" },6 { name: "Fred", age: 55, sex: "M" },7 { name: "Liz", age: 26, sex: "F" },8 { name: "Bill", age: 10, sex: "M" },9 { name: "Susan", age: 30, sex: "F" },10];
jsxDoing this without higer-order functions would be a pain. But, using higher order functions we can write a couple of functions and re-use them.
1// Function to filter on given sex2const sexFilter = (person, sex) => person.sex === sex;3
4// Get All Males5const allMales = people.filter((person) => sexFilter(person, "M"));6
7// Get All Females8const allFemales = people.filter((person) => sexFilter(person, "F"));9
10// Average Function to get average age11const average = (person) =>12 person.reduce((acc, cur) => acc + cur.age, 0) / person.length;13
14// Return oldest person15const oldest = (person) => person.sort((a, b) => b.age - a.age)[0];
jsxWith these 5 functions we can now answer all of the above questions:
1// 1. Average of everyone's age2average(people); // 32.253
4// 2. Average age of each sex.5average(allMales); // 36.56average(allFemales); // 287
8// 3. Oldest of each sex9oldest(allMales); // {name: "Jon", age: 60, sex: "M"}10oldest(allFemales); // {name: "Sandra", age: 40, sex: "F"}
jsxThis is beauty of higher-order functions we can write one function and re-use it over and over again regardless of the data we feed into it or how we want to mix them together.