Skip to content Skip to sidebar Skip to footer

Why Is Callback Function Executed First In Javascript?

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

Solution 1:

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.

Solution 2:

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

No, it is not. You are invokinglname (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:

functionprintsSomething() {
  console.log("Something");
}
functioninvokesCallbackAtEnd(callback) {
  console.log("invokesCallbackAtEnd doing something");
  callback();
}
functioninvokesCallbackAtStart(callback) {
  callback();
  console.log("invokesCallbackAtStart doing something");
}
functioninvokesCallbackAtStartAndEnd(callback) {
  callback();
  console.log("invokesCallbackAtStartAndEnd doing something");
  callback();
}
functioninvokesCallbackNever(callback) {
  console.log("invokesCallbackNever doing something");
}
invokesCallbackAtEnd(printsSomething); console.log("---");
invokesCallbackAtStart(printsSomething); console.log("---");
invokesCallbackAtStartAndEnd(printsSomething); console.log("---");
invokesCallbackNever(printsSomething); console.log("---");

Solution 3:

You aren't defining a callback function as such, to do so you will have to pass the reference to the function rather than the function call itself. i.e fname(lname); And you have to change your function fname to

function fname(cb){
  console.log("Billy");
  cb && cb.apply(this);
}

Solution 4:

You did not pass lname as a callback function. You just invoked lname function and passed its return value undefined.

And even if you passed a callback function, its execution point depends on code.

functionfname(func) {
  func("Foo");
  console.log("Billy");
  func("Bar");
}

functionlname() {
  console.log("Smith");
  returnfunction (arg) { console.log(arg); }
}
fname(lname());

Post a Comment for "Why Is Callback Function Executed First In Javascript?"