Donovant
Donovant

Reputation: 3161

Why Javascript load into a function "functions as parameters" before than variables?

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") );

Upvotes: 1

Views: 54

Answers (3)

b4rtekb
b4rtekb

Reputation: 136

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"); });

Upvotes: 0

Cerbrus
Cerbrus

Reputation: 72857

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"); });

Upvotes: 5

Barmar
Barmar

Reputation: 780871

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.

Upvotes: 8

Related Questions