1

The "fn" console.log comes up before than console.log of the two variables.

My function is that:

function test1(var1, var2, fn){ 
   console.log(var1, var2);
   fn();
}

function test2(var3){
   console.log(var3 + " it's here");
}

Call:

test1(123, "Hello!", test2("Look") );
20
  • 1
    Before you can call test1, you need to know the values of all of its arguments. test2("Look") must be evaluated first. Commented Aug 5, 2014 at 8:48
  • 1
    @Donovant: Nooo, it was not obvious. -1 Commented Aug 5, 2014 at 8:49
  • 1
    @LiviuM. If you'd have read the whole question, you would have seen what parameters were passed to test1. Commented Aug 5, 2014 at 8:53
  • 1
    @EvanKnowles: Since when do parameter names have anything to do with the names of the passed variables (/functions)? Commented Aug 5, 2014 at 8:54
  • 2
    Then why bother commenting with a cryptic "Nooo, it was not obvious. -1"? If you're going to comment about your downvote, at least give a suggestion on how the Q/A could be improved, instead of simply saying "Bad question -1" Commented Aug 5, 2014 at 8:59

3 Answers 3

8

You're not passing a function as the third argument, you're calling the function and passing its returned value. It should be:

test1(123, "Hello!", function() { test2("Look"); });

In addition to get the the wrong order of output, you should also be getting an error when you try to call fn(), since fn is undefined.

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

Comments

5

When you call test1(123, "Hello!", test2("Look") );, this is what's happening:

  • execute test2("Look")
  • Pass the return value from that function call to test1: test1(123, "Hello!", undefined);

Basically, test2 is executed before test1 is called, because you pass the return value of the function as a parameter.

To actually pass the function itself, to execute "later", you'll need to wrap it in an anonymous function:

test1(123, "Hello!", function() { test2("Look"); });

Comments

0

code should looks like:

(function(){
function test1(var1, var2, fn){ 
   console.log(var1, var2);
   fn("Look");
}

function test2(var3){
   console.log(var3 + " its here");
}

test1(123, "Hello!", test2);
})();

BTW "it's here" - ' (single quotation mark) got more power then " (double quotation mark). It should looks like 'it\'s here' or "it\'s here".

and if you want to call the passing function it should looks like @Cerbrus and @Barmar said:

test1(123, "Hello!", function() { test2("Look"); });

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.