What is a callback function?
- A function passed as an argument inside of a function that will be executed later
When to use a callback ?
- You can use callbacks in asynchronous functions, where one function has to wait for another function to invoke.
Regular Function :
function name(argument){
//do something
}
Callback Function :
//Defining functions
function prepare(ingredients, callback) {
console.log("Preparing " + ingredients);
callback();
}
//callback function
function chop(){
console.log("Chopping");
}
//Calling the function
prepare("onions and garlic", chop);
function createQuote(quote, callback){
var myQuote = "Like I always say, " + quote;
callback(myQuote); // 2
}
function logQuote(quote){
console.log(quote);
}
createQuote("eat your vegetables!", logQuote); // 1
// Result in console:
// Like I always say, eat your vegetables!
Things to know about callback functions :
- It's a function that is passed as an argument to another function
- Does not have to be named 'callback' in the argument
- This function is called a higher-order function which contains the logic for when the callback function gets executed
- JavaScript has anonymous functions which lets you declare and execute functions without naming them.
- Callback functions can be anonymous functions
Resources:
- https://www.freecodecamp.org/news/javascript-callback-functions-what-are-callbacks-in-js-and-how-to-use-them/#:~:text=As%20we%20can%20see%2C%20the,task%20as%20the%20example%20above.
- https://developer.mozilla.org/en-US/docs/Glossary/Callback_function#:~:text=A%20callback%20function%20is%20a,kind%20of%20routine%20or%20action.&text=The%20above%20example%20is%20a,as%20it%20is%20executed%20immediately.
- https://www.w3schools.com/js/js_callback.asp
Top comments (0)