What is a callback?
The callback is a function that is used as an argument of another function and this way function is able to call another function.
Sounds a little complicated, doesnât it? Letâs break it downâŠ
First, understand how functions run in JavaScript
In JavaScript, the functions run according to the order you called (told them to start executing) not according to the order you defined (wrote) them.
Defining function:
function first() {
return âI am firstâ;
}
function second() {
return âI am secondâ;
}
Calling a function in reversed order:
second();
first();
Which one is going to be called first?
The one we called first - second(); and as a result, we will see the output âI am secondâ;
However, sometimes there are situations when we want to control which functions run when, and calling them in a specific order is not enough. Here is an example of why itâs not always helpful.
Option 1
Defining function:
function displayResults(results) {
//some code running
document.getElementById(âresultsâ).innerHTMLÂ = results;
}
function googleSomething(keyword) {
//some code running
return searchResults;
}
Calling function in the desired order:
Let searchKeyword = googleSomething(âHow to JavaScriptâ);
displayResults(searchKeyword);
Why Option 1 is not always useful?
Because you will have to constantly call all the functions and when you have a lot of functions it can get messy and you might end up with extra functions you don't need or forget them. Any other reasons? Comment down below.
Option 2
Defining function:
function displayResults(results) {
//some code running
document.getElementById(âresultsâ).innerHTMLÂ = results;
}
function googleSomething(keyword) {
//some code running
displayResults(searchResults);
}
Calling only search function:
googleSomething(âHow to JavaScriptâ);
Why Option 2 is not always useful?
Because you will not be able to prevent the googleSomething function not to display the searchResults, it will always run displayResults function inside it.
How can a callback help in this case?
Instead of writing the function call manually or running the function when you donât need it, you can use a callback function instead. What you will do this way, is that the second function (the callback function) is not going to run until the first function is ready to return the result. To be short, if you donât run the first function, the second one will never run.
Defining function:
function displayResults(results) {
//some code running
document.getElementById(âresultsâ).innerHTMLÂ = results;
}
function googleSomething(keyword, displayResults) {
//some code running
displayResults(searchResults);
}
Calling only search function :
googleSomething(âHow to JavaScriptâ, displayResults);
The second argument displayResults in the googleSomething function is a callback! And a quick note: when passing a function as a callback you donât need to invoke it, just pass the name, no need for parenthesis.
When do I need to use the callback function?
First, you need to understand what an asynchronous function is. There is a lot about it but I will try to explain it as simply and as accurately as I can.
There are types of functions in JavaScript that are asynchronous - they do not run in sync with the whole code. They will need to execute a code that might take a lot of time and instead of stopping everything, they work in the back.
Let's take a silly example like McDonald's (not a big fan of McDonald's) - when you order a meal you move on and wait for its preparation.
Meanwhile, others also make their orders while you are waiting. All the people in the queue are not going to wait until you order until your meal is completed and until you take that meal. It would take so much time to serve each customer, right?
Not a great example but I think it is something similar to some extent. Your order preparation function will be asynchronous in this case. While people make orders or wait, the food preparation function is in the process of execution.
So once again, what will be the callback function in this case?
The callback function is called callback for a reason! The function says, âcall me back!â. Letâs say finally, our asynchronous function of food preparation has finished its execution and is ready to give you a result. And you want to run another function before receiving this result, a callback function that will call your name and the order name!
But you donât want someone to call your name only when your food is ready, right? đ€
To achieve this, you are going to attach this âcall my nameâ function to the food preparation. So when the food preparation function is finished it will run a callback function that calls your name!
To be short, a callback function is an argument of another function that is executed only when the first one is done executing.
There are a lot of other interesting things about callbacks but letâs stop here just for the basic understanding.
Did it make any sense though? đ Please do let me know
Top comments (8)
Your post deserves more reactions!đIt is very well-explained and would help any beginner understand how callbacks function, which is a core concept of JavaScript.
You have gained a follower from a fellow writer and developer đđ I look forward to future content!
Thank you Bruno, I appreciate that!
Thank you!
Glad if that helped :))
ĐĄongratulations đ„ł! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up đ
Awesome! Thank you đđ»
Why those double asterisk in the params?
Ah, seems like it's an issue with the markdown, the text is supposed to be bold. I will fix that, thank you so much . And seems like when writing a code snippet it doesn't work. Learning something new every day :))