How to make an array of functions in javascript?

It’s very common to use array in our code to write the cleaner code especially when you are dealing with multiple variables. But the question is “Have you ever made an 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:

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 special so far and it’s usually how we do it in our daily life. After that, we have declared an array named “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.

The same operation can be performed by using the iteration also:

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 the above example? So this is how we write cleaner and well-maintained code using arrays.

Leave a Reply