In JavaScript, a callback function is a function that is passed as an argument to another function and is executed inside that function. The purpose of a callback function is to allow you to execute code after a particular task has been completed.
Here is an example of a callback function in JavaScript:
function fetchData(url, callback) { fetch(url) .then(response => response.json()) .then(data => callback(data)) .catch(error => console.error(error)); } function handleData(data) { console.log(data); } fetchData('https://example.com/data', handleData);
In this example, the fetchData
function takes two arguments: a URL and a callback function. It uses the fetch
API to retrieve data from the specified URL, then passes that data to the callback function provided as the second argument.
The handleData
function is the callback function in this example. It simply logs the data to the console.
When the fetchData
function is called with the URL and handleData
function as arguments, the fetchData
function retrieves the data and calls the handleData
function with the retrieved data as its argument.
Callbacks are commonly used in JavaScript for asynchronous tasks such as making API requests, waiting for user input, or performing complex calculations that may take a while to complete.