In JavaScript, a callback is a function that is passed as an argument to another function and is executed after the completion of that function or at a specified event. Callbacks are commonly used in asynchronous programming to handle tasks like handling events, making HTTP requests, and processing data.
Here's a simple example to illustrate the concept of callbacks in JavaScript:
// Example 1: Synchronous Callback
// Function that takes a callback
function greet(name, callback) {
console.log(`Hello, ${name}!`);
// Execute the callback function
callback();
}
// Callback function
function sayGoodbye() {
console.log("Goodbye!");
}
// Calling the greet function with the sayGoodbye callback
greet("John", sayGoodbye);
// Output:
// Hello, John!
// Goodbye!
In this example, the greet
function takes a name
parameter and a callback
parameter. After greeting the person with their name, it executes the provided callback function. The sayGoodbye
function is passed as a callback when calling greet
, and it prints "Goodbye!" after the greeting.
Now, let's look at an example involving asynchronous operations, like a simulated HTTP request using setTimeout
:
// Example 2: Asynchronous Callback
// Simulating an asynchronous operation (e.g., HTTP request) with setTimeout
function simulateHTTPRequest(callback) {
console.log("Sending HTTP request...");
// Simulate delay with setTimeout
setTimeout(function () {
console.log("HTTP response received!");
// Execute the callback function
callback();
}, 2000); // Simulating a 2-second delay
}
// Callback function
function processResponse() {
console.log("Processing HTTP response...");
}
// Calling the function with the processResponse callback
simulateHTTPRequest(processResponse);
// Output:
// Sending HTTP request...
// (After 2 seconds)
// HTTP response received!
// Processing HTTP response...
In this example, the simulateHTTPRequest
function simulates an asynchronous operation with a 2-second delay using setTimeout
. It takes a callback function (processResponse
), which is executed after receiving the simulated HTTP response.
These examples demonstrate the fundamental concept of callbacks in JavaScript, both in synchronous and asynchronous contexts. Callbacks are crucial in handling asynchronous tasks, making them a fundamental part of modern JavaScript development.