MDN says that a callback is a function that is passed as an argument to another function. As far as I understand, it means callback is included within parentheses. This is the link.
But, I once came across an article on Freecodecamp saying that callback is a function that is similarly described by MDN, while a callback function is a function that is included in another function block. It means that callback function acts as the child function.
Am I wrong or there’s just some confusion between the two sources?
3
Answers
A callback is ANY function that passed to another function as an argument and meant to be called back, invoked somewhere inside the receiver function. The rest isn’t so important. You can assign a function to a variable and pass the variable as a callback too since in JS function are first-class objects, instances of the
Function
class/function.A function defined within the scope of another function is called a closure
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
A function passed as an argument to another function is called a callback
https://developer.mozilla.org/en-US/docs/Glossary/Callback_function
Update
Don’t worry about the terminology that much, the key takeaways here should be
The word
callback
means that a function will be called back by some code at some point in time. The wordcallback
doesn’t specify or mean the way how callback function is defined.Usually, a callback is a function passed as an argument to another function. The body of the callback function can reside in a global scope or within the other function or class method.
For example:
In this case, the body of the callback is defined in the global space, and it is passed as an argument to
setTimeout
.Second option:
In this case, the callback is defined in the body of another function,
startMyTimer
, and passed as an argument tosetTimeout
.Third option:
Here the body of the callback is declared within the
setTimeout
function call and passed into it as a parameter.Array example:
This example demonstrates that callbacks do not necessarily need to be passed as a parameter but can also be stored in variables or arrays.
Saved callback scenario, based on @slebetman’s comment:
This shows that a callback can be saved as a field of an object and then executed after some work is done.
Please let me know if this helps.