DEV Community

Cover image for Callback in JavaScript
Mofijul Haque
Mofijul Haque

Posted on • Edited on

1

Callback in JavaScript

A callback in JavaScript is a function that is passed as an argument to another function and is executed after the outer function has completed its task.

For example, let's say we have a function called "getData" that retrieves data from a server. We want to display this data on the page after it is retrieved, so we pass a callback function as an argument to "getData" that will handle the display of the data.

`
function getData(callback) {
// code to retrieve data from server
let data = "Retrieved Data";

// execute callback function with data as the argument
callback(data);
Enter fullscreen mode Exit fullscreen mode

}

function displayData(data) {
console.log(data);
}

getData(displayData); // logs "Retrieved Data" to the console
`

In this example, the "displayData" function is passed as a callback to the "getData" function. When "getData" retrieves the data from the server, it executes the "displayData" function, passing the retrieved data as an argument. This allows us to separate the logic of retrieving the data from the logic of displaying the data, making the code more modular and easier to maintain.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (2)

Collapse
 
osideeq profile image
Lanre Sideeq

well said

Collapse
 
mofijulhaque profile image
Mofijul Haque

Thank you 😊

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more