How to make an array of functions in javascript?

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:

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:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *