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

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (2)

Collapse
 
osideeq profile image
Lanre Sideeq

well said

Collapse
 
mofijulhaque profile image
Mofijul Haque

Thank you 😊

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs