javascript
  1. javascript-callback

JavaScript Callback

A callback function is a function passed as an argument to another function. When the first function has finished its task, it invokes the callback to share the result. Callbacks provide a way to make a program run asynchronously, which means that the code execution will continue even before the result from a function is ready.

Syntax

function sampleFunction(callback){
  // code to execute
  // invoke the callback when the task is complete 
  callback();
}

Example

function doSomething(task, callback) {
  console.log(`Starting ${task}...`);
  callback();
}

doSomething('Task 1', function() {
  console.log('Task 1 complete');
});

doSomething('Task 2', function() {
  console.log('Task 2 complete');
});

doSomething('Task 3', function() {
  console.log('Task 3 complete');
});

Output

Starting Task 1...
Task 1 complete
Starting Task 2...
Task 2 complete
Starting Task 3...
Task 3 complete

Explanation

In the above code snippet, doSomething is a function that takes two arguments, i.e., a task and a callback function. When doSomething is invoked with a task and a callback function, it will execute the task and then invoke the callback function. Inside the callback function, we have written the code that needs to be executed when the task is complete.

Use

Callbacks are widely used in JavaScript to make asynchronous programming possible. Some of the use cases are:

  • Handling events and user input
  • Making HTTP requests
  • Reading and writing files asynchronously

Important Points

  • Callbacks are functions that are passed as an argument to another function.
  • Callbacks are executed asynchronously, which means that the code will continue to execute even before the result from the function is ready.
  • Callbacks are used in events, asynchronous programming, and for handling errors.

Summary

JavaScript Callback is a function that is passed as an argument to another function. Callbacks are used to handle events, making HTTP requests, reading and writing files asynchronously, and for error handling. They provide a way to make a program run asynchronously. When the first function has finished its task, it invokes the callback to share the result.

Published on: