Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript callbacks - why are these processed in different order?

How come in this example, the 'second' function is exercised second:

<script>
function first (callback){
    alert ("I am first");
    callback();
}

function second (){
    alert ("I am second");
}

first(second);
</script>

But in this example, the second function is processed first. Why does adding the () after calling the second make a difference....

<script>
function first (callback){
    alert ("I am first");
    callback();
}

function second (){
    alert ("I am second");
}

first(second());
</script>
like image 892
John Avatar asked Dec 06 '25 07:12

John


1 Answers

Putting () after a variable holding a function will call that function.

first(second); calls first and passes the second function as an argument. first will then call callback which is the same as second

first(second()); calls second, then calls first and passes the return value of second() as the argument. first will then call undefined (and error) because that is the return value of second().

like image 163
Quentin Avatar answered Dec 08 '25 21:12

Quentin