WTF is Higher Order Function ?
Deepak Kumar
Posted on January 7, 2023
A higher-order function is a function that takes one or more functions as arguments, or returns a function as its result. Higher-order functions are often used in functional programming languages. They allow you to abstract over actions, rather than just values.
function applyTwice(func, arg) {
return func(func(arg));
}
function sum(x) {
return x + 5;
}
console.log(applyTwice(sum, 10)); // 20
In this example, applyTwice
is a higher-order function because it takes the function sum
as an argument and calls it twice on the argument 10.
Higher-order functions are often used in functional programming languages like JavaScript to abstract over actions, rather than just values. They can be used to create reusable abstractions that can simplify complex code and make it easier to understand.
Here are few examples of HOC functions in javascript :
-
Array.prototype.map()
: This function takes an array and a callback function as arguments, and returns a new array with the results of calling the callback function on every element in the original array.
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(x => x * 2);
console.log(doubledNumbers); // [2, 4, 6, 8, 10]
-
Array.prototype.filter()
: This function takes an array and a callback function as arguments, and returns a new array with only the elements from the original array that pass the test implemented by the callback function.
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(x => x % 2 === 0);
console.log(evenNumbers); // [2, 4]
- Array.prototype.reduce(): This function takes an array and a callback function as arguments, and returns a single value that is the result of applying the callback function to each element in the array, from left to right.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 15
- Array.prototype.sort(): This function takes an array and an optional compare function as arguments, and returns a new array with the elements in the original array sorted according to the return value of the compare function.
const numbers = [4, 1, 5, 2, 3];
const sortedNumbers = numbers.sort((a, b) => a - b);
console.log(sortedNumbers); // [1, 2, 3, 4, 5]
I hope you understand now what higher order functions are.
Thanks for reading. Follow me on Twitter
Posted on January 7, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.