What is Higher Order Function in JavaScript | JavaScript Tutorials in Hindi | Interview Question #50
In JavaScript, a Higher-Order Function is a function that either:
Takes one or more functions as arguments, or Returns a function as its result.
These functions are a powerful feature of JavaScript and functional programming, allowing for more abstract and concise code. Let’s look at both aspects with examples.
Functions as Arguments
Higher-order functions can accept other functions as arguments, allowing for operations like callbacks, event handling, and more.
const numbers = [1, 2, 3, 4, 5];
// Higher-order function 'map' that takes a function as an argument
const doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // Output: [2, 4, 6, 8, 10]
Here, the map
function is a higher-order function that takes a function as its argument. The provided function is applied to each element in the numbers
array, resulting in a new array with each element doubled.
Functions as Return Values
Higher-order functions can also return other functions, enabling the creation of function factories or generating functions dynamically.
function createMultiplier(multiplier) {
return function(num) {
return num * multiplier;
};
}
const double = createMultiplier(2);
const triple = createMultiplier(3);
console.log(double(5)); // Output: 10
console.log(triple(5)); // Output: 15
In this example, createMultiplier
is a higher-order function that returns a new function. The returned function multiplies its input by a specified multiplier. This allows you to create different multiplier functions (e.g., double
and triple
) with ease.
Common Higher-Order Functions in JavaScript
- Array.prototype.map: Transforms an array by applying a function to all of its elements.
- Array.prototype.filter: Creates a new array with all elements that pass the test implemented by the provided function.
- Array.prototype.reduce: Executes a reducer function on each element of the array, resulting in a single output value.
- Array.prototype.forEach: Executes a provided function once for each array element.
- Array.prototype.find: Returns the value of the first element in the array that satisfies the provided testing function.
Higher-order functions are a fundamental concept in JavaScript, enabling more expressive and concise code by leveraging the power of functions as first-class citizens.