Introduction
A callback function is one of the most important concepts in JavaScript. It allows one function to execute another function after completing a task. Callback functions are widely used in JavaScript for handling asynchronous operations such as API requests, file reading, event handling, and timers.
What is a Callback Function?
A callback function is a function that is passed as an argument to another function and is executed later.
In simple words:
A callback is a function that is called after another function finishes its work.
Syntax
function greeting() {
console.log("Good Morning!");
}
function welcome(callback) {
console.log("Welcome!");
callback();
}
welcome(greeting);
Output
Welcome!
Good Morning!
Explanation
-
greeting()is the callback function. -
welcome()accepts a function as a parameter. -
callback()executes thegreetingfunction after printing "Welcome!".
Real-Life Example
Imagine you order food at a restaurant.
- You place the order.
- The chef prepares the food.
- After the food is ready, the waiter serves it.
Here, serving the food happens only after preparation is complete.
This is exactly how callback functions work.
Example 1: Email Sending
function emailSent() {
console.log("Email Sent Successfully!");
}
function sendEmail(callback) {
console.log("Sending Email...");
callback();
}
sendEmail(emailSent);
Output
Sending Email...
Email Sent Successfully!
Example 2: Download File
function downloadComplete() {
console.log("Download Complete!");
}
function downloadFile(callback) {
console.log("Downloading File...");
callback();
}
downloadFile(downloadComplete);
Output
Downloading File...
Download Complete!
Why Do We Use Callback Functions?
Callback functions are useful because they:
- Execute code only after another task finishes.
- Improve code reusability.
- Handle asynchronous operations.
- Make event handling easier.
- Help avoid repeating code.
Where Are Callback Functions Used?
Some common uses include:
- API requests
- File operations
- Timers (
setTimeout) - Event listeners (
onclick,addEventListener) - Array methods like
forEach(),map(), andfilter()
Example Using setTimeout
function showMessage() {
console.log("Welcome after 3 seconds!");
}
setTimeout(showMessage, 3000);
Output (after 3 seconds)
Welcome after 3 seconds!
Here, showMessage is the callback function executed after 3 seconds.
Advantages
- Makes code flexible.
- Encourages code reuse.
- Essential for asynchronous programming.
- Simplifies event-driven programming.
Disadvantages
- Too many nested callbacks can make code difficult to read.
- Deep nesting leads to Callback Hell, which reduces code maintainability.
- Modern JavaScript often uses Promises and async/await to overcome these issues.
Conclusion
Callback functions are a fundamental part of JavaScript. They allow one function to execute after another function has completed its task. They are especially useful for asynchronous programming, event handling, timers, and API calls.
Top comments (0)