Q1. What is a Callback Function in JavaScript?
A callback function is a function that is passed as an argument to another function and is executed later.
Example
Output
Example
function greet(name, callback) { console.log("Hello " + name); callback();}
function sayBye() { console.log("Goodbye!");}
greet("Nikhil", sayBye);Output
Hello NikhilGoodbye!Q2. Why are Callback Functions used?
Callbacks are mainly used to:
- Handle asynchronous operations
- Execute code after another task finishes
- Improve code flexibility
- Event handling
- API requests
Q3. What is Asynchronous Programming?
Asynchronous programming allows JavaScript to run tasks without waiting for the previous task to complete.
Example
Output
JavaScript does not wait for setTimeout to finish.
Example
console.log("Start");
setTimeout(function() { console.log("Inside Timeout");}, 2000);
console.log("End");Output
StartEndInside TimeoutJavaScript does not wait for setTimeout to finish.
Q4. How do Callbacks help in Asynchronous Programming?
Callbacks allow functions to run after asynchronous operations complete, like:
Example
- Loading data
- Fetching API
- File reading
- Timer functions
Example
function fetchData(callback) { setTimeout(function() { console.log("Data Fetched"); callback(); }, 2000);}
fetchData(function() { console.log("Processing Data");});Q5. What is Callback Hell?
Callback Hell occurs when multiple nested callbacks make code difficult to read and maintain.
Example
This nested structure becomes messy and hard to debug.
Example
loginUser(function(user) { getUserPosts(user, function(posts) { getPostComments(posts, function(comments) { console.log(comments); }); });});This nested structure becomes messy and hard to debug.
