It’s very common to use array in our code to write the cleaner code specially when you are dealing with multiple variables. But the question is “Have you ever made array of functions?”. If your answer is No then this post is for you. Yes today we are going to learn that how to make an array of functions in javascript and we will also see how to use it.

Let’s move ahead and see the below example:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
function add(a, b) { return a + b; } function subtract(a, b) { return a - b; } function multiply(a, b) { return a * b; } function divide(a, b) { return a / b; } const methods = [ add, subtract, multiply, divide ]; console.log(methods[0](1, 2)); // Performs addition console.log(methods[1](10, 5)); // Performs Subtraction console.log(methods[2](10, 5)); // Performs Multiplication console.log(methods[3](10, 5)); // Performs Division |

In the above example we have defined methods for mathematical operations such as Addition, Subtraction, Multiplication and Division. There is nothing specially so far and it’s usually how we do it in our daily life. After that we have declared an array named as “methods” which holds our arithmetic functions. We have assigned the functions to our array and after that we called all functions by using the indices of the array.

Same operation can be performed by using the iteration also:

1 2 3 |
for(i in methods) { console.log(methods[i](10, 5)); } |

Did you notice how we made the array dynamic and reduced the lines of code in above example. So this is how we write cleaner and well maintained code using arrays.