DEV Community

Cover image for JavaScript Callbacks
Karthick (k)
Karthick (k)

Posted on

JavaScript Callbacks

A callback function is a function that is passed as an argument to another function and executed later.

  1. A function can accept another function as a parameter.

  2. Callbacks allow one function to call another at a later time.

  3. 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);

Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

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)