0

I ran across this problem when trying to populate a JS array for some animation I'm doing....the following Javascript function is invoked when I click a link within my web page for testing purposes:

function testing()
{
    var funcArray = [];
    var testFunc = function(){console.log("test function");}

    funcArray.push(function(){console.log("hello there");});
    funcArray.push(testFunc());
}

When this executes, I get "test function" to appear in the JS console, but not "hello there". Why does pushing the predefined testFunc cause output, but not the inline function in the first push?

3
  • 1
    Remove the function brackets. Only push the name, funcArray.push(testFunc); Commented Jul 18, 2015 at 20:48
  • 1
    Cause you are executing th function using () Commented Jul 18, 2015 at 20:48
  • Understood. Thanks much. Commented Jul 18, 2015 at 20:51

2 Answers 2

6

Because you're calling it.

funcArray.push(testFunc());

calls testFunc, then pushes the result of that call into funcArray. You probably want funcArray.push(testFunc); (note the omitted ()), which just pushes the function reference to that array.

Sign up to request clarification or add additional context in comments.

Comments

1

Because you execute it in funcArray.push(testFunc());... What you want is funcArray.push(testFunc); Because testFunc() executes the Function, takes the return and pushes it to the Array, while testFunc takes the actual function to push.

Comments

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.