Higher order functions and callbacks
2 min readJun 9, 2021
In a nutshell, higher-order functions are those functions that take other functions as arguments OR return other functions. The function passed as arguments in higher-order function is known as a callback.
JavaScript has some built-in higher-order functions such as map(), filter() and reduce().
map()
const numArray = [1, 5, 3, 6, 4, 7]; const increasedArray = numArray.map((element) => {
return element + 1;
}); console.log(increasedArray); // [2, 6, 4, 7, 5, 8]
filter()
let arr [1,2,3,4,5];const resultant Array = arr.filter((element ) => {
return element > 3;
})console.log(resultantArray); // [4, 5]
reduce()
const numArray = [1, 2, 3, 4, 5];const sum = numArray.reduce((total, num) => {
return total + num;
});console.log(sum);
Callbacks are nothing more that functions, that are passed as arguments to other functions.
Using the previous filter example…
let arr [1,2,3,4,5];
const resultant Array = arr.filter((element) => {return element>3})
console.log(resultantArray); // [4, 5]
… this would be the callback function we’re passing as an argument to the filter()
higher order function.
(element) => {return element>3}