23 Feb 2024




Intermediate

Callbacks in JavaScript refer to functions that are passed as arguments to other functions and are executed after some asynchronous operation is completed or when a certain condition is met. Callbacks are a fundamental concept in JavaScript, especially in asynchronous programming.

Basic example of how callbacks work:

// Example 1: Callback function
function doSomething(callback) {
  console.log("Doing something...");
  // Simulate an asynchronous operation
  setTimeout(function() {
    console.log("Operation completed.");
    callback(); // Execute the callback function
  }, 2000);
}

// Callback function
function callbackFunction() {
  console.log("Callback executed.");
}

// Call the function and pass the callback
doSomething(callbackFunction);

In this example:

  • The doSomething() function simulates an asynchronous operation using setTimeout().
  • It takes a callback function as an argument.
  • The callback function callbackFunction() is defined separately and passed as an argument to doSomething().
  • When the asynchronous operation completes after 2 seconds, the callback function callbackFunction() is executed.

Callbacks are often used in event handling, AJAX requests, timers, and other asynchronous operations in JavaScript.

However, as JavaScript has evolved, there are other asynchronous patterns and constructs like Promises, async/await, and event emitters that provide cleaner and more manageable alternatives to callbacks, especially when dealing with complex asynchronous flows. Promises, for instance, offer a more structured and elegant way to handle asynchronous operations and avoid callback hell (a situation where deeply nested callbacks become difficult to manage).

javascript
callbacks