Problem Statement
What is a callback function? Why is it important in JavaScript?
Explanation
A callback is a function you pass into another function to be executed later.
It allows asynchronous actions, meaning your program can continue working while waiting for something to finish.
Callbacks are essential in event handling, API calls, and timers.
They prevent blocking and make JavaScript responsive.
Before Promises and async await, callbacks were the main way to handle asynchronous behavior.
Mastering callbacks builds a strong base for understanding Promises and async programming.
Code Solution
SolutionRead Only
function fetchData(callback) {
setTimeout(() => {
console.log('Data ready');
callback();
}, 1000);
}
fetchData(() => console.log('Callback executed'));