JavaScript

What is callback in JavaScript? (callback function)

February 3, 2022

What is callback in JavaScript? (callback function)

In this article we will learn what is a callback in JavaScript, a type of function widely used in JavaScript, and we will also see practical use cases for this feature.

callback in JavaScript cover

Hey you programmer, ok? Let’s learn something new!

Callback in JavaScript is a feature in which we write a function inside another

This one will be performed only when necessary

That is, the resource is waiting for a certain action to be executed later.

Let’s take a practical example:

function firstFunction() {
 console.log('test callback');
}
window.addEventListener('click', firstFunction);

In this case, the firstFunction will only be executed after a click on the screen, before that, it is only prepared in the code

This is the concept of the callback, a function passed as an argument, which will only be called at the right time

Execution Order

Another important detail is the order of execution.

The callback is always invoked/executed after the main function is finished

So keep this in mind, so as not to create a problem in your logic.

Another Example

To further focus  your knowledge, let’s see another example

function testingCallback(a, b, callback) {
 console.log(a + b);
 callback();
}

testingCallback(1,2, function() {
 console.log('sum ready!')
});

Here we use a callback with an anonymous function, which alerts us when the sum is finished

Another practice that is perfectly acceptable

API Communication

Another good example of when we should use callback is when communicating with an API

Let’s say we need to do an action with a certain response from an API that can take some time

How are we going to do this action if we don’t know when the answer will come?

Simple! The answer is callback, we attach a callback function as an argument in the API route function call

Then it will be executed exactly when the answer arrives, that is, a perfect case for this resource to be used

Conclusion

In this article we learned what is callback in JavaScript

Basically a function that takes as a parameter another function

This being passed by parameter executed last, that is, when the source function is completely finished

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x