16. Can you explain the concept of callbacks in JavaScript? Also provide an example to support your explanation.
Callbacks are functions passed as arguments to other functions. The function receiving the callback is called when a certain event occurs, such as after an API call has completed or when an error has occurred during a process.
Here's an example of how callbacks work:
function makeAPICall(url, successCallback, errorCallback) {
// code to make API call goes here
}
makeAPICall('https://api.example.com', (data) => {
console.log(data);
}, (error) => {
console.log(error);
});
In this example, the `makeAPICall()` function takes three arguments: the URL to call, a success callback function, and an error callback function. When the API call is complete, the data is passed as an argument to the success callback function, which logs it to the console. If an error occurs during the call, the error message is passed as an argument to the error callback function, which also logs it to the console.
The `makeAPICall()` function only knows about two types of callbacks - success and error. Depending on the API being called, there may be other callbacks available that can be used to handle different types of events.