What are Callbacks?
1. Definition
A callback is a function that is passed as an argument to another function and is executed later, usually after a task is completed.
2. Key Idea
- Function passed as a parameter
- Executed after a task finishes
- Used in asynchronous programming
- Core concept in Node.js
3. How it Works
- A function is defined
- Another function is passed as an argument
- After task completion, callback is executed
4. Example
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
function sayBye() {
console.log("Goodbye!");
}
greet("Manaswini", sayBye);👉 Output:
Hello Manaswini Goodbye!
5. Async Example (Node.js)
const fs = require("fs");
fs.readFile("file.txt", "utf-8", (err, data) => {
if (err) throw err;
console.log("File content:", data);
});👉 Callback runs after file reading is complete.
6. Types of Callbacks
- Synchronous Callback
- Asynchronous Callback
7. Callback Hell
When multiple callbacks are nested inside each other, it becomes hard to read and maintain the code.
doTask1(() => {
doTask2(() => {
doTask3(() => {
console.log("Done");
});
});
});8. Solution
- Use Promises
- Use async/await
- Improve code readability
9. Advantages
- Handles asynchronous tasks
- Non-blocking execution
- Simple to implement
10. Disadvantages
- Callback hell
- Hard to debug
- Less readable for complex logic
Interview Points
- Callback is a function passed as argument
- Executed after task completion
- Used for async programming
- Can lead to callback hell