In JavaScript, higher-order functions are functions that can take other functions as arguments, or return a function as a result. They allow us to write more modular and reusable code and are an essential concept in functional programming.
Let’s take a closer look at higher-order functions and how they can be used in JavaScript.
Passing Functions as Arguments: One of the primary use cases for higher-order functions is to pass other functions as arguments. This allows us to write functions that can take on different behavior depending on the functions that are passed to them.
For example, we can write a higher-order function that takes an array and a function, and applies that function to each element in the array:
function applyFuncToEachElement(arr, func) {
var result = [];
for (var i = 0; i < arr.length; i++) {
result.push(func(arr[i]));
}
return result;
}
// Define a function to pass as an argument
function square(x) {
return x * x;
}
// Use the higher-order function to apply the function to each element in the array
var arr = [1, 2, 3, 4, 5];
var result = applyFuncToEachElement(arr, square);
console.log(result); // [1, 4, 9, 16, 25]
In this example, we define a higher-order function called applyFuncToEachElement
that takes an array and a function as arguments. We then define a function called square
that we will pass as an argument to applyFuncToEachElement
. Finally, we use the higher-order function to apply the square
function to each element in the array.
Returning Functions as Results: Another common use case for higher-order functions is to return a function as a result. This allows us to write functions that can create other functions based on certain input parameters.
For example, we can write a higher-order function that takes a number and returns a function that multiplies other numbers by that number:
function multiplyBy(num) {
return function(x) {
return x * num;
}
}
// Use the higher-order function to create a new function that multiplies by 5
var multiplyBy5 = multiplyBy(5);
console.log(multiplyBy5(2)); // 10
console.log(multiplyBy5(3)); // 15
In this example, we define a higher-order function called multiplyBy
that takes a number as an argument and returns a new function. The returned function takes a number as an argument and multiplies it by the original number passed to the multiplyBy
function. Finally, we use the higher-order function to create a new function that multiplies by 5 and use it to multiply the numbers 2 and 3.
Using Built-in Higher-Order Functions: JavaScript provides several built-in higher-order functions, such as map
, filter
, and reduce
, that are commonly used for working with arrays.
For example, we can use the map
function to apply a function to each element in an array and return a new array with the results:
var arr = [1, 2, 3, 4, 5];
var result = arr.map(function(x) {
return x * x;
});
console.log(result); // [1, 4, 9, 16, 25]
In this example, we use the map
function to apply the square
function to each element in the array and return a new array with the squared values.
let’s take a look at filter
and reduce
as well.
filter
: The filter
function is used to create a new array with all elements that pass a certain test. It takes a function as an argument that returns a boolean value indicating whether the element should be included in the new array.
For example, we can use filter
to create a new array with all even numbers from an existing array:
var arr = [1, 2, 3, 4, 5];
var evenNumbers = arr.filter(function(x) {
return x % 2 === 0;
});
console.log(evenNumbers); // [2, 4]
In this example, we define a new array called evenNumbers
by using the filter
function to create a new array with only the even numbers from the original array.
reduce
: The reduce
function is used to apply a function to each element in an array and reduce the array to a single value. It takes a function as an argument that defines the reduction operation, and an initial value for the reduction.
For example, we can use reduce
to sum up all the elements in an array:
var arr = [1, 2, 3, 4, 5];
var sum = arr.reduce(function(acc, x) {
return acc + x;
}, 0);
console.log(sum); // 15
In this example, we define a new variable called sum
by using the reduce
function to add up all the elements in the original array, starting with an initial value of 0.
Question on Reduce: Suppose you have an array of functions and you want to call each function but you have to use the output of the previous function in the array.
Answer: an example of using the reduce
method with API data:
const arrayOfFunctions = [
async function () {
const data = await fetchDataFromApi();
return data.value;
},
async function (previousResult) {
const updatedData = await updateData(previousResult);
return updatedData.newValue;
},
async function (previousResult) {
const transformedData = await transformData(previousResult);
return transformedData.finalValue;
}
];
const result = await arrayOfFunctions.reduce(async (accumulatorPromise, currentFunction) => {
const accumulator = await accumulatorPromise;
return currentFunction(accumulator);
}, Promise.resolve(null));
console.log(result); // Output: finalValue
In this example, we define the array of functions as async functions that fetch and transform data from an API. We then use the reduce
method to apply each function in the array to the previous result.
On the first iteration, we start with a promise that resolves to null
(since the initial value of the result is null
). We then call the first function to fetch data from the API, and we await the result to get the value
. On the second iteration, we call the second function to update the data from the API with the previous value and we await the result to get the newValue
. On the final iteration, we call the third function to transform the data from the API and we await the result to get the finalValue
.
So the final result is finalValue
, which is the output of the last function in the array when it’s passed the result of all the previous functions that retrieved and transformed data from the API.
In conclusion, higher-order functions are an important concept in JavaScript and functional programming. They allow us to write more modular and