2

This code adds functions to an array :

    var fArr = []
    fArr.push(test())
    fArr.push(test())

    function test(){
        console.log('here')
    }

However the function test() is invoked each time its added to array fArr

Can the function test() be added to the array fArr without invoking the function ?

I'm attempting to populate the array fArr with functions and then iterate over fArr and invoke the functions, not invoke the functions as they are being added to fArr which is current behavior.

fiddle : http://jsfiddle.net/3fd83oe1/

blue-sky
  • 51,962
  • 152
  • 427
  • 752

2 Answers2

6

Yes, you can add functions to an array. What you're actually doing is invoking the functions and adding the result of the function invocation to the array. What you want is this:

fArr.push(test);
fArr.push(test);
Ethan Brown
  • 26,892
  • 4
  • 80
  • 92
2

It's as simple as:

fArr.push(test, test);

Examples

var fArr = []

function test() {
    return 'here';
}


fArr(test, test);     
// > Array [ function test(), function test() ]
// Because test evaluates to itself

fArr(test(), test());
// > Array [ "here", "here" ]
// Because test() evaluates to 'here'
Nabil Kadimi
  • 10,078
  • 2
  • 51
  • 58