techStackGuru

JavaScript Callback function


Callback functions are functions that are invoked by another function and passed as arguments to it. As a result of the callback function in JavaScript, asynchronous operations can be performed.

In scenarios where a function must wait for an operation to finish before continuing its execution, callbacks are commonly used. The asynchronous function provides a callback as a parameter instead of blocking the programs execution and waiting for the operation to complete. During the completion of the operation, the function can execute other code. After an operation is completed, the callback function is called, often with the operations result.

Syntax

function fetchData(url, callback) {
    // Simulating an asynchronous operation (e.g., AJAX request, setTimeout)
    setTimeout(function() {
      const data = "Some data fetched from " + url;
      callback(data); // Invoke the callback function with the data
    }, 2000); // Delay of 2 seconds
  }
  
  function processData(data) {
    console.log("Processed data: " + data);
  }
  
  fetchData("https://www.apidata.com/value", processData); 

The fetchData function in the above code simulates an asynchronous operation by introducing a 2 second delay using the setTimeout method. As soon as the operation is complete, the fetched data is passed to the callback function. It logs the processed data to the console through the processData function passed as the callback.

Example - Event Handling:

// Example 1: Event handling with a callback
document.getElementById("myButton").addEventListener("click", function() {
  console.log("Button clicked!");
}); 

Using the anonymous function in this example, the "click" event of the button with the ID "myButton" is handled. Callback function is invoked when button is clicked, logging a message to console.

Example - Array Iteration:

// Example 2: Array iteration with a callback
const numbers = [1, 2, 3, 4, 5];

numbers.forEach(function(number) {
  console.log(number * 2);
}); 

In this example, each element of the numbers array is iterated over with the forEach method. Every element is invoked by an anonymous function passed as a callback. Each number is multiplied by 2 and the result is logged to the console.


You can do asynchronous operations in JavaScript by using callbacks, which allow you to handle asynchronous results without blocking other code. AJAX requests, event handling, and timers are all common uses of them in JavaScript APIs and libraries.

Example - Addtion of numbers

function display(sumData) {
  console.log(sumData) //5
}

function add(num1, num2, myCallback) {
  let sum = num1 + num2;
  myCallback(sum);
}

add(2, 3, display); 

previous-button
next-button