Callbacks in JavaScript
Callbacks
55
In JavaScript, a callback is a function that is passed as an argument to another function and is executed after some operation has been completed. The function that accepts the callback is responsible for calling it at the appropriate time.
Callbacks are commonly used in asynchronous programming, where a function does not immediately return a result but instead relies on a callback to handle the result once it is available. For example, when making an AJAX request to a server, a callback function is passed as an argument to the AJAX function, and is executed once the request has been completed and the response has been received.
Here's an example:
function getData(callback) { setTimeout(function() { const data = [1, 2, 3, 4, 5]; callback(data); }, 1000); } getData(function(data) { console.log(data); });
In this example, the getData
function accepts a callback as an argument, which is executed after a 1-second delay. The callback function receives an array of data, which is then printed to the console.
Callbacks are a fundamental concept in JavaScript and are used heavily in many frameworks and libraries. Learning how to use them effectively is essential for writing efficient and scalable JavaScript code.
March 25, 2023