Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is callback function executed first in javascript? [duplicate]

In the below example. lname is callback function inside fname function. When executed, first output is Smith and the Billy. As per my understanding, callback function lname should be executed once fname function is finished executing. Why am wrong here?

function fname(){ console.log("Billy");}
function lname(){ console.log("Smith");}
fname(lname());
like image 351
vegabond Avatar asked Mar 22 '26 06:03

vegabond


2 Answers

In the below example. lname is callback function inside fname function.

No, it is not. You are invoking lname (because you added the parentheses), and passing the result of its invocation (which happens to be undefined, as is the case any time a function does not explicitly return a value) to fname. Just like Math.floor(Math.sqrt(10)) - there are no callbacks here. There is a big difference between fname(lname()) and fname(lname): the latter one passes a function itself into another function; and we'll call it a "callback" if it is, in fact, called back.

As per my understanding, callback function lname should be executed once fname function is finished executing.

Again, no. A callback is executed when it is invoked, no more, no less. For example:

function printsSomething() {
  console.log("Something");
}
function invokesCallbackAtEnd(callback) {
  console.log("invokesCallbackAtEnd doing something");
  callback();
}
function invokesCallbackAtStart(callback) {
  callback();
  console.log("invokesCallbackAtStart doing something");
}
function invokesCallbackAtStartAndEnd(callback) {
  callback();
  console.log("invokesCallbackAtStartAndEnd doing something");
  callback();
}
function invokesCallbackNever(callback) {
  console.log("invokesCallbackNever doing something");
}
invokesCallbackAtEnd(printsSomething); console.log("---");
invokesCallbackAtStart(printsSomething); console.log("---");
invokesCallbackAtStartAndEnd(printsSomething); console.log("---");
invokesCallbackNever(printsSomething); console.log("---");
like image 170
Amadan Avatar answered Mar 23 '26 20:03

Amadan


The arguments to a function are evaluated before it's called. So fname(lname()) results in lname being called, followed by fname. The result of lname is passed to fname as the first argument but it is not used by the called function.

like image 45
jspcal Avatar answered Mar 23 '26 18:03

jspcal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!