High order functions are functions that take another function as a paramater or return another function.
You see in javascript functions can be treated as variables as well so it makes it possible to return them or pass them as params.
Implementing a high order function
Let's implement a simple high order function that takes another function and call it inside it's body
function doSomething(action) {
action(); // Hi
}
function actionFunction() {
console.log("Hi");
}
doSomething(actionFunction);
we called the doSomething function and gave it the function actionFunction as param and it simply called it inside it's body and that's perfectly fine in javascript
let's create anothet high order function but now we will instead return a function from it
function getAction() {
return function() {
console.log("Hi");
}
}
const action = getAction();
action(); // hi
we stored the function returned by getAction then called it afterwards to log hi to the console
Existing high order functions in Javascript
javascript has a lot of high order functions built in the language, now let's see some of them that are array methods
the forEach method
let arr = [1, 2, 3, 4, 5];
function log(x) {
console.log(x); // 1, 2, 3, 4, 5
}
arr.forEach(log);
the forEach function loops through the array and each time it calls the passed function and give it the element currently iterating on
the map function
let arr = [1, 2, 3, 4, 5];
function double(x) {
return x * 2;
}
const newArr = arr.map(double);
console.log(newArr); // [ 2, 4, 6, 8, 10 ]
the map method replaces the value that is currently iterating on with the value that the passed function returns and then returns the new array
the filter method
let arr = [1, 2, 3, 4, 5];
function isPair(x) {
return x % 2 == 0;
}
const pairs = arr.filter(isPair);
console.log(pairs); // [ 2, 4 ]
the filter method will only keep array elements that are passed to the function and returns true
Top comments (0)