Ever called a friend and told them to call you back? That’s exactly what a callback function is in JavaScript! It’s a function passed as an argument to another function, so it can be executed later. Think of it like ordering a pizza —you place the order (function call) and wait for the delivery guy (callback) to bring your delicious pizza when it’s ready.
1. Basic Example
A callback function is simply a function passed to another function as an argument. Here’s a simple example:
function greet(name, callback) {
console.log("Hello, " + name);
callback();
}
function sayGoodbye() {
console.log("Goodbye!");
}
greet("Alice", sayGoodbye);
Output:
Hello, Alice
Goodbye!
Real-life analogy: Like saying “Hi” to your friend, and they respond with a “Bye” before leaving.
2. Callbacks in Asynchronous JavaScript
Callbacks are super useful when dealing with asynchronous operations like fetching data from a server, reading files, or setting timeouts.
Example with setTimeout
:
console.log("Start");
setTimeout(() => {
console.log("This runs after 2 seconds");
}, 2000);
console.log("End");
Output:
Start
End
This runs after 2 seconds
Real-life analogy: Like putting instant noodles in hot water and waiting for them to be ready.
3. Callback Hell
When using nested callbacks, your code can become messy and hard to read. This is known as callback hell (or Pyramid of Doom).
function step1(next) {
console.log("Step 1");
setTimeout(next, 1000);
}
function step2(next) {
console.log("Step 2");
setTimeout(next, 1000);
}
function step3(next) {
console.log("Step 3");
setTimeout(next, 1000);
}
step1(() => {
step2(() => {
step3(() => {
console.log("All steps completed!");
});
});
});
Real-life analogy: Like calling your friend, who calls another friend, who calls another friend… until you forget who you were even talking to.
4. Avoiding Callback Hell with Promises
To solve this, JavaScript introduced Promises which make asynchronous code more readable:
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function runSteps() {
console.log("Step 1");
await wait(1000);
console.log("Step 2");
await wait(1000);
console.log("Step 3");
console.log("All steps completed!");
}
runSteps();
Real-life analogy: Instead of making multiple phone calls, you just send a scheduled email.
5. When to Use Callbacks?
Callbacks are useful when:
- You need to execute code after something happens (like waiting for user input).
- Handling asynchronous operations (API requests, reading files, timers, etc.).
- Writing higher-order functions that take functions as arguments (like
map
,filter
, andreduce
).
Conclusion
Callbacks are powerful but can be tricky when overused. If you ever find yourself deep in callback hell, consider using Promises or async/await!
0 Comments