1. What is a callback function in JavaScript?
A callback function is a function passed as an argument to another function, to be executed later. Callbacks are used for asynchronous operations like reading files, making API calls, or handling events. The function receiving the callback decides when to execute it. Callbacks are fundamental to JavaScript's asynchronous programming model. Modern JavaScript often uses Promises and async await instead of callbacks to avoid callback hell.
// Simple callback example
function greet(name, callback) {
console.log('Hello ' + name);
callback();
}
function sayBye() {
console.log('Goodbye!');
}
greet('John', sayBye);
// Output:
// Hello John
// Goodbye!
// Array methods use callbacks
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(num) {
console.log(num * 2);
});
// Asynchronous callback
setTimeout(function() {
console.log('This runs after 2 seconds');
}, 2000);
// Event listener callback
button.addEventListener('click', function() {
console.log('Button clicked!');
});
// Callback with parameters
function processData(data, successCallback, errorCallback) {
if (data) {
successCallback(data);
} else {
errorCallback('No data');
}
}
processData('Hello',
function(result) { console.log('Success:', result); },
function(error) { console.log('Error:', error); }
);