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());
In the below example.
lnameis callback function insidefnamefunction.
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
lnameshould be executed oncefnamefunction 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("---");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With