Categories
JavaScript Answers

How to Create an Array of Functions with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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