A callback function is a function that is passed as an argument to another function and executed later.
A function can accept another function as a parameter.
Callbacks allow one function to call another at a later time.
A callback function can execute after another function has finished.
function greet(name, callback) {
console.log("Hello, " + name);
callback();
}
function sayBye() {
console.log("Goodbye!");
}
greet("Ajay", sayBye);
Working of Callbacks in JavaScript
JavaScript executes code line by line (synchronously), but sometimes we need to delay execution or wait for a task to complete before running the next function. Callbacks help achieve this by passing a function that is executed later.
Callbacks for Asynchronous Execution
console.log("Start");
setTimeout(function () {
console.log("Inside setTimeout");
}, 2000);
console.log("End");
When to Use and Avoid Callbacks
Use callbacks when
- Handling asynchronous tasks (API calls, file reading).
- Implementing event-driven programming.
- Creating higher-order functions.
Avoid callbacks when:
- Code becomes nested and unreadable (use Promises or async/await).
- You need error handling in asynchronous operations (Promises are better).
Top comments (0)