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/

1
  • 1
    test() is executing your function, just do .push(test) Commented Nov 19, 2014 at 18:08

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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'

1 Comment

+1 for reminding us that Array.prototype.push takes multiple arguments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.