Callback functions in JavaScript are functions that are passed as arguments to other functions and are executed at a later point in time. They allow us to control the flow of execution and perform actions asynchronously.
Here is an example of a callback function in JavaScript:
function fetchData(callback) { // Simulating an asynchronous operation setTimeout(function() { const data = 'Some data'; callback(data); }, 2000); } function processData(data) { console.log('Processing data:', data); } fetchData(processData);
In this example, the fetchData function takes a callback function as an argument. It simulates an asynchronous operation using setTimeout and after 2 seconds, it calls the callback function with the fetched data. The processData function is the callback function that receives the data and processes it.
Using HTML format for the answer:
<!DOCTYPE html> <html> <head> <title>Callback Function Example</title> <script> function fetchData(callback) { // Simulating an asynchronous operation setTimeout(function() { const data = 'Some data'; callback(data); }, 2000); } function processData(data) { console.log('Processing data:', data); } fetchData(processData); </script> </head> <body> <h1>Callback Function Example</h1> <p>Check the browser console for the output.</p> </body> </html>
You can save the above code in an HTML file and open it in a web browser to see the output in the browser console.