Callback in another function
A callback function can be passed simply as an argument when calling another function - since in JavaScript functions are values (first-class citizens).
Example:
javascript
function doSomething(callback) {
console.log('Doing something...');
callback(); // call the passed callback
}
function afterDone() {
console.log('Done!');
}
doSomething(afterDone);Output:
javascript
Doing something...
Done!You can pass an anonymous callback directly at the call site:
javascript
doSomething(() => {
console.log('Done!');
});Summary: To pass a callback, specify it as a parameter when calling the function. And inside the receiving function, call it by name when it needs to run.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.