1. Explain Callback functions and some scenarios where they are used.
A callback function is a function passed into another function as an argument. This function is then
invoked inside the outer function to complete a certain task. Callbacks are often used for
asynchronous operations like:
- Reading files
- Making API calls
- Event handling
Example:
function fetchData(callback) {
setTimeout(() => {
callback('Data loaded');
}, 1000);
fetchData(message => [Link](message));
2. How will you handle errors in a callback function?
Errors in callback functions are typically handled using the 'error-first' callback pattern. The first
argument of the callback is reserved for an error object. If an error occurs, it is passed to the
callback; otherwise, null is passed.
Example:
function doTask(callback) {
let error = true;
if (error) {
callback('An error occurred', null);
} else {
callback(null, 'Task completed');
doTask((err, result) => {
if (err) {
[Link](err);
} else {
[Link](result);
});