What is a callback?
The callback is a function that is used as an argument of another function and this way function can 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. Here is an example.
Define two functions
Then call both functions but in a reversed order
Which function is going to be called first?
The one we called first, the function named second. As a result, we will see the output âI am secondâ, even though we initially wrote the other function first. This means that it doesn't matter which one we created first, what matters is who we called first.
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
Define two functions:
Call the functions in the desired order:
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 from displaying 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. 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 background.
Let's take a silly example like McDonald's or any fast-food chain - 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 place an order, your meal is ready, 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 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.
Once again, what will the callback function be in this case?
The callback function is called callback for a reason! The function says it all, âcall me back!â.
Imagine, our asynchronous function of food preparation has finished its execution and is ready to give you a result. 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. As a result, 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 :))