DEV Community

Cover image for JavaScript Callbacks
Ekaterine Mitagvaria
Ekaterine Mitagvaria

Posted on • Updated on

JavaScript Callbacks

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”;
}
Enter fullscreen mode Exit fullscreen mode

Calling a function in reversed order:

second();
first();
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

Calling function in the desired order:

Let searchKeyword = googleSomething(“How to JavaScript”);
displayResults(searchKeyword);
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

Calling only search function:

googleSomething(“How to JavaScript”);
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

Calling only search function :

googleSomething(“How to JavaScript”, displayResults);
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
bcostaaa01 profile image
Bruno

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!

Collapse
 
catherineisonline profile image
Ekaterine Mitagvaria

Thank you Bruno, I appreciate that!

Collapse
 
sergey_yozh profile image
sergey-yozh

Thank you!

Collapse
 
catherineisonline profile image
Ekaterine Mitagvaria

Glad if that helped :))

Collapse
 
fruntend profile image
fruntend

ĐĄongratulations đŸ„ł! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍

Collapse
 
catherineisonline profile image
Ekaterine Mitagvaria

Awesome! Thank you đŸ™ŒđŸ»

Collapse
 
moshfiqrony profile image
Md. Moshfiqur Rahman Rony

Why those double asterisk in the params?

Collapse
 
catherineisonline profile image
Ekaterine Mitagvaria • Edited

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 :))