Reputation: 215
I am really struggling with callback functions. I understand that callback functions are functions that are passed as a parameter to other functions. However, I thought that as soon as the interpreter would see that we have passed a function as parameter, it will identify it as a callback function and will therefore run it at the end, i.e. after everything else has been executed.
Just to confirm this I tried the following bit of code:
newFunction = (x,y,z, callback) => {
callback();
let sum = x + y + z;
console.log(sum);
}
newerFunction = () => {
console.log("This is the callback function");
}
newFunction(2,3,4,newerFunction)
If my understanding was correct, I should have first seen the sum logged into the console and only then should the callback have been called, upon which I should have seen the "This is the callback function" statement.
However, this DID NOT HAPPEN, instead the callback function ran first, and the sum was logged second. I understand that I have put it in this order in the newFunction, however, if the callback gets executed after everything else than the sum should have been logged first.
I also know that callbacks aren't necessarily asynchronous and so in this case it must be synchronous, but then my overall understanding of the concept is really inadequate and inaccurate.
Kindly help.
I am positive I understood the concept well earlier, I have revisited the concept after sometime and am really struggling with it.
Many thanks
Upvotes: 0
Views: 166
Reputation: 162
Upvotes: 1
Reputation: 191
A callback is a function A
passed as an argument to another function B
for which we know that B
will call A
at a given time. This may happen immediately as in a synchronous callback (which is your example), or it might happen at a later time as in an asynchronous callback.
A function being a callback does not define the exact timing of its execution as this is up to the caller to decide. All we know is that it is going to be called (hence the name).
Upvotes: 1
Reputation: 944441
However, I thought that as soon as the interpreter would see that we have passed a function as parameter, it will identify it as a callback function and will therefore run it at the end, i.e. after everything else has been executed.
No.
Callback functions have to be explicitly called by the function they are passed to. The JS engine has no idea what arguments you need to pass to the callback or what to do with the return value it emits.
They run at the point you call them.
Take Array.prototype.forEach()
for example.
The design of the function is to call the callback function you pass to it once for every member of an array. It would be pretty useless if it ran only once, at the end.
const array = [5, 4, 3, 2, 1];
const callback = member => console.log(member);
array.forEach(callback);
Upvotes: 1