This answer was really helpful for me, although I did encounter some difficulties when trying to call each function in my array multiple times. So, for those who are beginners like me, here is a simple guide on how to create an array of functions and how to call either one or all of them in a few different ways.
Let's start by creating the array.
let functionsArray = [functionOne, functionTwo, functionThree];
To call a specific function in the array, you can use its index (remember that the index starts at 0).
functionsArray[0]();
Don't forget to include the parentheses after the function name to actually call it.
If you want to call all the functions in the array, there are a couple of different methods you can use.
Using a For Loop
for (let index = 0; index < functionsArray.length; index++) {
functionsArray[index]();
}
Make sure to include the parentheses to execute the function.
Using ForEach
ForEach is convenient because you don't have to worry about the index; the function element is automatically passed to you. You can use it as shown below (using a non-arrow function example):
functionsArray.forEach(element => {
element();
});
In a ForEach loop, you can rename the variable element
as you wish. Here's an example without using arrow functions:
functionsArray.forEach(
function(funFunctionPassedIn) {
funFunctionPassedIn();
}
);
What about Map?
It's not recommended to use Map in this scenario, as it creates a new array. Using Map when we don't need the new array is considered an anti-pattern (not a good practice).
We should avoid using map if we're not utilizing the returned array or if we're not returning a value from the callback. Source