Junior — Middle
What is meant by callback in programming?
sobes.tech AI
Answer from AI
A callback in programming is a function that is passed as an argument to another function and is invoked after a certain action or event is completed. It allows organizing asynchronous execution and result handling.
For example, in JavaScript:
function fetchData(callback) {
setTimeout(() => {
const data = { id: 1, name: 'Test' };
callback(data); // call callback after data is received
}, 1000);
}
fetchData(function(result) {
console.log('Data received:', result);
});
Here, fetchData takes a callback and calls it after a delay, simulating an asynchronous operation. The callback handles the result when it becomes available.