A callback function is a function that is passed as an argument to another function and is executed inside that function. In JavaScript, callback functions are often used to handle asynchronous operations, such as making HTTP requests or working with timers. In this guide, we'll provide an overview of callback functions and provide some code examples.
What is a Callback Function?
A callback function is simply a function that is passed as an argument to another function and is executed inside that function. In other words, it is a function that is called back by another function.
Example of a Callback Function
Here is a simple example of a callback function:
javascriptfunction myFunction(callback) {
// Do something here
callback();
}
function myCallback() {
console.log('The callback function was called');
}
myFunction(myCallback);
In this example, we define a function called myFunction
that takes a single argument called callback
. We then define a second function called myCallback
that simply logs a message to the console.
When we call myFunction
and pass myCallback
as an argument, myFunction
executes the code inside it, and then calls the callback
function (which is myCallback
). When the callback
function is called, it logs a message to the console.
Using a Callback Function for Asynchronous Operations
One of the most common uses for callback functions in JavaScript is for handling asynchronous operations, such as making HTTP requests. Here's an example:
javascriptfunction makeRequest(url, callback) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if (xhr.status === 200) {
callback(null, xhr.responseText);
} else {
callback(xhr.statusText, null);
}
};
xhr.onerror = function() {
callback('An error occurred', null);
};
xhr.send();
}
function handleResponse(error, response) {
if (error) {
console.error(error);
} else {
console.log(response);
}
}
makeRequest('https://api.example.com/data', handleResponse);
In this example, we define a function called makeRequest
that takes a URL and a callback function as arguments. Inside makeRequest
, we create a new XMLHttpRequest
object and set its properties. We then define an onload
function that checks the response status code and calls the callback function with either an error or the response text.
We also define an onerror
function that simply calls the callback function with an error message if something goes wrong.
Finally, we define a handleResponse
function that logs the response to the console if there is no error, and logs the error if there is one.
When we call makeRequest
and pass handleResponse
as the callback function, makeRequest
makes an HTTP request to the specified URL and calls the handleResponse
function with either an error or the response text.
That's it! We hope this guide has been helpful in understanding callback functions and how to use them in JavaScript.