51. What is a higher order function? Explain with the help of relevant examples.
A higher-order function (HOF) is a function that takes one or more functions as arguments and/or returns a function as its output. In other words, it operates on functions themselves and can manipulate them in various ways.
Here are some examples of HOFS:
`map()` method in JavaScript - The `map()` method applies a function to each element of an array and returns a new array with the results.
function double(x) {
return x * 2;
}
let numbers = [1, 2, 3];
let doubledNumbers = numbers.map(double);
console.log(doubledNumbers); // [2, 4, 6]
In this example, the `map()` method takes a function (`double`) and applies it to each element of an array (`numbers`) to return a new array with the doubled values.
`filter()` method in JavaScript - The `filter()` method creates a new array containing only elements for which the provided function returns true.
function isEven(x) {
return x % 2 === 0;
}
let numbers = [1, 2, 3, 4];
let evenNumbers = numbers.filter(isEven);
console.log(evenNumbers); // [2, 4]
In this example, the `filter()` method takes a function (`isEven`) and applies it to each element of an array (`numbers`) to return a new array containing only even numbers.
`reduce()` method in JavaScript - The `reduce()` method applies a function to accumulate values from an array into a single output value.
function sum(x, y) {
return x + y;
}
let numbers = [1, 2, 3];
let total = numbers.reduce(sum, 0);
console.log(total); // 6
In this example, the `reduce()` method takes a function (`sum`) and applies it to each element of an array (`numbers`) to accumulate their values into a single output value (`total`). The second argument (`0`) is the initial value for the accumulation.
In summary, a higher-order function is a function that takes one or more functions as arguments and/or returns a function as its output. Examples of HOFS include `map()`, `filter()`, and `reduce()` methods in JavaScript, which operate on arrays of numbers and perform various operations on them using functions.