What is a JavaScript callback function? Give an Examples
Sam: Asking about JavaScript callback functions
Lingaraj: Now, giving that answer,
As you know, in JavaScript, a callback function is a function that is passed as an argument to another function and is executed after the completion of some asynchronous operation or a certain event. Callback functions are commonly used in scenarios such as handling asynchronous operations, event handling, and in functions like setTimeout
or setInterval
.
Here are some examples to illustrate the use of callback functions:
1. Callbacks for Asynchronous Operations:
// Simulating an asynchronous operation with setTimeout
function fetchData(callback) {
setTimeout(() => {
const data = 'Some fetched data';
callback(data);
}, 2000); // Simulating a 2-second delay
}
// Callback function to handle the fetched data
function handleData(data) {
console.log('Data received:', data);
}
// Using the fetchData function with a callback
fetchData(handleData);
2. Callbacks for Event Handling:
// Simulating an event listener with a callback
function buttonClickHandler(callback) {
// Simulating a button click event
console.log('Button clicked!');
callback();
}
// Callback function for the button click event
function handleButtonClick() {
console.log('Handling button click...');
}
// Using the buttonClickHandler function with a callback
buttonClickHandler(handleButtonClick);
3. Callbacks in Array Methods:
// Using forEach with a callback
const numbers = [1, 2, 3, 4, 5];
function logNumber(number) {
console.log(number);
}
numbers.forEach(logNumber);
// Using map with a callback to transform array elements
const squaredNumbers = numbers.map(function (number) {
return number * number;
});
console.log('Squared numbers:', squaredNumbers);
4. Callbacks in Promises:
// Using a Promise with a callback function
const fetchDataPromise = new Promise(function (resolve, reject) {
setTimeout(() => {
const data = 'Some fetched data';
resolve(data);
}, 2000); // Simulating a 2-second delay
});
// Handling the resolved value with a callback
fetchDataPromise.then(function (data) {
console.log('Data received:', data);
});
Conclusion:
These examples demonstrate different scenarios where callback functions are commonly used. Callbacks are a fundamental concept in JavaScript, especially in asynchronous programming, and they provide a way to handle operations that might take some time to complete or respond to events.