Understanding Callbacks in JavaScript
A callback is a function passed into another function as an argument, then invoked later inside that function to complete a routine or action.
๐ Why Use Callbacks?
JavaScript is asynchronous and non-blocking. Callbacks help manage operations that take time, such as network requests or reading files.
๐งช Basic Example
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
function sayBye() {
console.log("Goodbye!");
}
greet("Alice", sayBye);
Output:
Hello Alice
Goodbye!
โฑ With setTimeout
setTimeout(function() {
console.log("Executed after 2 seconds");
}, 2000);
๐ Callback as Function Parameter
function processUserInput(callback) {
const name = "Bob";
callback(name);
}
processUserInput(function(name) {
console.log("User's name is " + name);
});
โ ๏ธ Callback Hell
Too many nested callbacks can lead to unreadable code.
doSomething(function(result1) {
doSomethingElse(result1, function(result2) {
doMore(result2, function(result3) {
// ...
});
});
});
โ ๏ธ Tip: Use
Promises
or async/await
to avoid callback hell.
๐ Summary
- Callbacks are used to run code after a task completes.
- They allow asynchronous, non-blocking operations.
- Can be anonymous functions or named functions.