What is a Callback Function in JavaScript
Updated on 05th Jan, 24 9.1K Views

Through this blog, we will dive into the concept of a callback function in JavaScript, along with its needs and examples. Moving forward, you will understand synchronous and asynchronous callback functions, their respective codes, and more.

Let us explore the following topics:

Watch this video on Full Stack Web Development Course:

What is a Callback Function in JavaScript?

A callback function in JavaScript is a type of function that is passed as an argument to another function. This function is then called inside the parent function to complete a routine or an action. In simpler words, the callback function will always be executed after its parent function (the function in which it is passed as an argument) has done its execution.

Let us understand how we can create a callback function in JavaScript with the help of the following code:

// Step 1: Define a function that takes a callback as an argument
function fetchData(callback) {
  // Simulate an asynchronous operation (e.g., fetching data from an API)
  setTimeout(function () {
    const data = { message: "Data fetched successfully in Intellipaat!" };
    // Step 3: Call the callback function and pass the data
    callback(data);
  }, 2000); // Simulating a delay of 2 seconds
}
// Step 2: Define a callback function
function handleData(data) {
  console.log(data.message);
}
// Step 4: Call the main function and pass the callback function
fetchData(handleData);
// Output:
// Data fetched successfully in Intellipaat! (after a 2-second delay)

Let’s break down the steps:

Define a function that takes a callback as an argument (Step 1):

In this example, the fetchData function is defined to simulate an asynchronous operation using setTimeout. It takes a callback function (callback) as an argument.

Define a callback function (Step 2):

The handleData function is defined as a callback function. It will be executed when the asynchronous operation inside the fetchData function is completed.

Call the callback function (Step 3):

Inside the fetchData function, after the asynchronous operation is complete (simulated by setTimeout), the callback function (callback) is called with the fetched data as an argument.

Call the main function and pass the callback function (Step 4):

Finally, the fetchData function is called, and the handleData function is passed as a callback. This is where the actual asynchronous operation takes place, and the callback function is executed when the operation is complete.

Check out these Web Development Courses to get an in-depth understanding of web development!

Why Do We Need a Callback Function in JavaScript?

Let us find out the need for a callback function in JavaScript:

  • Callback functions use asynchronous programming in JavaScript, which makes code safe from errors and bugs.
  • Callback function in JavaScript always makes sure that no function is going to execute before a task is completed but will always run right after the task is executed.
  • These types of functions are responsible for creating interactive and dynamic web pages, as when an event occurs (e.g., a button click, a key press, or an HTTP request completion), a callback function is invoked in response to that particular event.
  • Callback functions like setTimeout and setInterval promote modularity and reusability. This enhances the code’s maintainability and reduces redundancy.

Various Examples of Callback Functions in JavaScript

Hence, we understand the need for a callback function in JavaScript. Let us now move on to the various examples this function offers:

setTimeout()

The setTimeout() function is a classic example of using a callback in JavaScript to execute code after a specified delay. It takes two parameters: a function to be executed and the time delay in milliseconds. 

For instance,

console.log("Start");
setTimeout(function() {
  console.log("Delayed message");
}, 2000); // Executes the callback function after a 2-second delay
console.log("End");

In this example, “Start” and “End” are logged first, and after a 2-second delay, “Delayed message” is logged due to the callback function.

promise.then()

When working with promises, the .then() method is often used to handle asynchronous operations. The .then() method takes a callback function as an argument, and it executes that function when the promise is resolved. 

Here’s an example:

const myPromise = new Promise((resolve, reject) => {
  // Simulating an asynchronous operation
  setTimeout(() => {
    resolve("Promise resolved!");
  }, 2000);
});
myPromise.then((result) => {
  console.log(result); // Logs "Promise resolved!" after the promise is resolved
});

In this case, the callback function within .then() is executed once the promise is resolved.

Go through these most frequently asked 55 Verilog Interview Questions with detailed answers to excel in your career in 2024.

Async/Await

Using async/await is another way to work with asynchronous code in a synchronous-looking manner. The async keyword is used to define a function that returns a promise, and await is used to pause the execution until the promise is resolved. 

Here’s an example:

 async function fetchData() {
 // Simulating an asynchronous operation
  let result = await new Promise((resolve) => {
    setTimeout(() => {
      resolve("Async data");
    }, 2000);
  });
  console.log(result); // Logs "Async data" after the promise is resolved
}
fetchData();

Here, the await keyword is used to wait for the promise to resolve, and the callback function is executed after the asynchronous operation is complete.

addEventListener()

The addEventListener() method is commonly used to handle events in the browser. It takes an event type and a callback function, which is executed when the specified event occurs. 

For example,

const button = document.getElementById('myButton');
button.addEventListener('click', function() {
  console.log("Button clicked!"); // Executes the callback when the button is clicked
});

In this case, the callback function is triggered when the specified button is clicked, demonstrating the use of callbacks in event handling.

Check out our JavaScript Interview Questions to crack high-paying, top-level MNC interviews.

Get 100% Hike!

Master Most in Demand Skills Now !

Synchronous and Asynchronous Callback Functions in JavaScript

In this section, we will understand the concept of synchronous and asynchronous callback functions in JavaScript and their proper implementation:

Synchronous Callback Function in JavaScript

Synchronous callback functions are the type of function that execute instantly. These functions follow a sequence when they are executed. This means that priority will be given to the first callback compared to the second callback during execution whenever the function calls two synchronous callbacks. 

Synchronous callbacks are mostly used when we have to do something at that particular interval of time, such as modify the user interface or call an API. 

Here is the code for the synchronous callback function:

function doSomething(callback) {
  console.log("Doing something...");
  // Simulating a task that takes some time
  for (let i = 0; i < 3e6; i++) {
    // This loop is just for simulating a time-consuming task
  }
  console.log("Task complete!");
  // Calling the callback function once the task is complete
  callback();
}
function callbackFunction() {
  console.log("Callback function executed! In Intellipaat");
}
// Calling the function with the synchronous callback
doSomething(callbackFunction);

Output:

Doing something…
Task complete!
Callback function executed! In Intellipaat

In this example, doSomething is a function that takes a callback function (callback) as an argument. Inside doSomething, there’s a simulated time-consuming task (a for loop), and once that task is complete, it calls the provided callback function (callback()).

The callbackFunction is a simple function that just logs a message. When you call doSomething(callbackFunction), it will print messages to the console in a synchronous manner. 

Keep in mind that synchronous callbacks can potentially block the execution of the rest of your code until they are complete.

Asynchronous Callback Function in JavaScript

Asynchronous callback functions are another type of function that are executed randomly. As a result, with this function, you can’t predict when the asynchronous callback will be executed. For managing the respective tasks that require more time, such as network requests, asynchronous callbacks are crucial. 

The code for the asynchronous callback function is as follows:

function doSomethingAsync(callback) {
  console.log("Doing something asynchronously in Intellipaat...");
  // Simulating an asynchronous task with setTimeout
  setTimeout(function () {
    console.log("Async task complete!");
    // Calling the callback function once the asynchronous task is complete
    callback();
  }, 2000); // Simulating a 2-second delay
}
function callbackFunction() {
  console.log("Callback function executed!");
}
// Calling the function with the asynchronous callback
doSomethingAsync(callbackFunction);

Output:

Doing something asynchronously in Intellipaat…
(2-second delay)
Async task complete!
Callback function executed!

In the provided JavaScript code, the function doSomethingAsync is designed to execute an asynchronous task and accept a callback function as an argument. When invoked with callbackFunction, the asynchronous process begins by logging “Doing something asynchronously in Intellipaat…” to the console. 

To simulate the asynchronous nature, the code utilizes setTimeout, introducing a 2-second delay before proceeding. Following this delay, the message “Async task complete!” is logged, indicating the completion of the asynchronous operation. 

Subsequently, the callback function (callbackFunction) is invoked, leading to the logging of “Callback function executed!” to the console. This pattern of asynchronous callbacks proves beneficial in scenarios where tasks involve time-consuming operations, enabling the rest of the code to continue execution without being blocked during the asynchronous task’s completion.

Want to learn more about web development? Read our comprehensive guide on Web Development Tutorial now!

When to Use the Callback Function in JavaScript

There are particular criteria for using the callback function in JavaScript. Those are as follows:

  • We can use the callback function when you are performing an asynchronous task, such as AJAX requests, reading files, or executing any operations that are not completed immediately.
  • Callback functions are used with promises to handle the resolved or rejected states.
  • These types of functions are widely used for error handling in asynchronous operations.

Advantages of the Callback Function in JavaScript

 Here are some advantages of using callback functions in JavaScript:

  • Callbacks can make use of closures, allowing them to access variables from their containing scope even after that scope has finished execution. This provides a way to maintain state across multiple calls.
  • Callbacks are crucial for managing the order of execution in both sequential and parallel scenarios. You can chain callbacks to ensure certain operations are performed in a specific order or use them to run tasks concurrently.
  • Asynchronous callbacks enable non-blocking code execution. This means that while one operation is being processed, other operations can continue to execute, improving the overall efficiency and responsiveness of the application.
  • Callbacks play a fundamental role in the event loop mechanism of JavaScript, which manages the execution of code and events. This provides concurrency without the need for multi-threading.

Things to Be Aware of When Using Callbacks

In the above section, we have seen the various advantages of a callback function in JavaScript. Moving further, you should also be aware of a few things while using callback functions in JavaScript.

  • Callback Hell: While using a callback function, always avoid excessive nesting of a callback for better readability.
  • Error Handling: Try to manage errors effectively, as callback-based code can make error handling more complex.
  • State Management: Be cautious with state maintenance across asynchronous operations.
  • Parameter Consistency: Ensure consistent parameter lists for callbacks.
  • Overreliance Warning: Avoid overusing callbacks and consider alternative patterns for improved clarity.

Career Transition

Non-Tech to IT Associate | Career Transformation | AWS Certification Course - Intellipaat Reviews
Non Tech to DevOps Engineer Career Transition | Intellipaat Devops Training Reviews - Nitin
Upskilled & Got Job as Analyst After a Career Break |  Data Science Course Story - Shehzin Mulla
Successful Career Change after Completion of AWS Course - Krishnamohan | Intellipaat Review
Got Job Promotion After Completing Artificial Intelligence Course - Intellipaat Review | Gaurav
Intellipaat Reviews | Big Data Analytics Course | Career Transformation to Big Data | Gayathri

Wrap Up

We have discussed all the important things crucial for any student who wants to learn about callback functions in JavaScript. This function in JavaScript also plays a vital role in the IT industry, as it helps the developer improve their application performance with minimal errors, which will save you time and effort.

Have you got more queries? Come to our Community and get them clarified today!

Course Schedule

Name Date Details
Web Development Courses 02 Mar 2024(Sat-Sun) Weekend Batch
View Details
Web Development Courses 09 Mar 2024(Sat-Sun) Weekend Batch
View Details
Web Development Courses 16 Mar 2024(Sat-Sun) Weekend Batch
View Details

Leave a Reply

Your email address will not be published. Required fields are marked *

Speak to our course Advisor Now !

Related Articles

Subscribe to our newsletter

Signup for our weekly newsletter to get the latest news, updates and amazing offers delivered directly in your inbox.