Categories
JavaScript Answers

How to Create an Array of Functions with JavaScript?

Spread the love

Sometimes, we want to create an array of functions with JavaScript.

In this article, we’ll look at how to create an array of functions with JavaScript.

Put Functions in an Array

We can put functions in an array as we do with any other values.

For instance, we can write:

const firstFunction = () => {
  //...
}

const secondFunction = () => {
  //...
}

const thirdFunction = () => {
  //...
}

const forthFunction = () => {
  //...
}

const arr = [
  firstFunction,
  secondFunction,
  thirdFunction,
  forthFunction
]

arr[0]()
arr[1]()
arr[2]()
arr[3]()

We have 4 functions, firstFunction , secondFunction , thirdFunction , and forthFunction .

And then we put them all in the arr array, separating them with commas.

Finally, we can call them by getting the function by their index from arr and call them as we do with any other function.

Conclusion

We can put functions in an array as we do with any other values in JavaScript.

So we can create a JavaScript array with functions as values.

Leave a Reply

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