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