
What is callback ?
A JavaScript callback is a function passed into another function as an argument, which is then invoked (called back) inside the outer function to complete some kind of routine or action. Callbacks are a way to ensure certain code doesn’t execute until other code has already finished execution, particularly useful for handling asynchronous operations such as API calls, reading files, or timers.
Why Use Callbacks?
Callbacks are used to:
- Ensure that code executes in the correct order.
- Handle asynchronous operations.
- Improve the readability and maintainability of code by separating concerns.
Example of a Simple Callback
Here’s a basic example where a callback function is used:
function greeting(name) {
console.log(`Hello, ${name}!`);
}
function processUserInput(callback) {
const name = prompt('Please enter your name.');
callback(name);
}
processUserInput(greeting);
In this example, greeting
is a callback function passed to processUserInput
. When processUserInput
is executed, it collects user input and then calls greeting
with the user’s name.
Asynchronous Callbacks
Callbacks are especially useful for asynchronous operations, such as handling HTTP requests or reading files. Here’s an example using setTimeout
, a built-in function for scheduling a callback to run after a delay:
function sayHello() {
console.log('Hello!');
}
console.log('Before setTimeout');
setTimeout(sayHello, 2000); // sayHello will be called after 2 seconds
console.log('After setTimeout');
Output:
Before setTimeout
After setTimeout
Hello!
In this example, sayHello
is executed after a 2-second delay, demonstrating how callbacks can be used to schedule asynchronous operations.
Example with an API Call
Suppose you want to fetch data from an API. You can use the fetch
function which returns a promise. Here’s how you could use a callback to handle the fetched data:
function fetchData(url, callback) {
fetch(url)
.then(response => response.json())
.then(data => callback(data))
.catch(error => console.error('Error fetching data:', error));
}
function displayData(data) {
console.log('Received data:', data);
}
const apiUrl = 'https://api.example.com/data';
fetchData(apiUrl, displayData);
In this example, fetchData
fetches data from the given URL and then calls displayData
with the received data. This showcases the power of callbacks in handling asynchronous operations like HTTP requests.
Conclusion
Callbacks are a fundamental concept in JavaScript, enabling asynchronous programming and helping to control the execution flow of your code. They enhance the flexibility and readability of code, particularly in situations where you need to wait for some operations to complete before continuing.