JavaScript Functions - Higher-Order Functions


In JavaScript, higher-order functions are functions that operate on other functions. They can take functions as arguments, return functions, or both. Higher-order functions are a fundamental concept in functional programming and are widely used in JavaScript for tasks like mapping, filtering, and reducing arrays. In this guide, we'll explore the concept of higher-order functions with practical examples.


Example 1: Functions as Arguments


In this example, we'll create a higher-order function called operate that takes two numbers and a function as arguments. The function parameter specifies the operation to be performed on the two numbers:


function operate(a, b, operation) {
return operation(a, b);
}
function add(x, y) {
return x + y;
}
function subtract(x, y) {
return x - y;
}
const result1 = operate(5, 3, add);
const result2 = operate(8, 2, subtract);
console.log('Addition result:', result1); // Outputs: 8
console.log('Subtraction result:', result2); // Outputs: 6

Example 2: Functions as Return Values


In this example, we'll create a higher-order function called multiplyBy that takes a number and returns a function. The returned function multiplies its argument by the number provided to multiplyBy:


function multiplyBy(factor) {
return function(x) {
return x * factor;
}
}
const double = multiplyBy(2);
const triple = multiplyBy(3);
console.log('Double of 5:', double(5)); // Outputs: 10
console.log('Triple of 4:', triple(4)); // Outputs: 12

Example 3: Using Built-in Higher-Order Functions


JavaScript provides several built-in higher-order functions like map(), filter(), and reduce() for working with arrays. In this example, we'll use map() to double each element in an array:


const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(function(number) {
return number * 2;
});
console.log('Doubled numbers:', doubledNumbers); // Outputs: [2, 4, 6, 8, 10]

Conclusion


Higher-order functions are a powerful and flexible concept in JavaScript. They enable you to create more reusable and expressive code by passing and returning functions as values. You can apply these functions to a wide range of programming tasks, making your code more functional and concise.


Explore the use of higher-order functions in your projects to simplify and enhance your JavaScript code.