Javascript Array of Functions

Nick picture Nick · Feb 5, 2011 · Viewed 192.3k times · Source
var array_of_functions = [
    first_function('a string'),
    second_function('a string'),
    third_function('a string'),
    forth_function('a string')
]

array_of_functions[0];

That does not work as intended because each function in the array is executed when the array is created.

What is the proper way of executing any function in the array by doing:

array_of_functions[0];  // or, array_of_functions[1] etc.

Thanks!

Answer

Darin Dimitrov picture Darin Dimitrov · Feb 5, 2011
var array_of_functions = [
    first_function,
    second_function,
    third_function,
    forth_function
]

and then when you want to execute a given function in the array:

array_of_functions[0]('a string');