DEV Community

gaurbprajapati
gaurbprajapati

Posted on

Complete Concept Callback function in javascript

> In JavaScript, a callback function is a function that is passed as an argument to another function and is invoked or called at a specific point within that function. The purpose of a callback function is to allow asynchronous or non-blocking operations to be executed in a sequential manner.

In JavaScript, functions are treated as first-class objects, which means they can be assigned to variables, passed as arguments to other functions, and returned from functions. This flexibility allows us to define a function and pass it as a callback to another function.

Here's a simple example to illustrate the concept of a callback function:

function doSomething(callback) {
  // Perform some tasks

  // Invoke the callback function
  callback();
}

function callbackFunction() {
  console.log("Callback function executed!");
}

// Pass callbackFunction as a callback to doSomething
doSomething(callbackFunction);
Enter fullscreen mode Exit fullscreen mode

In the example above, doSomething is a function that takes a callback function as an argument. Inside doSomething, it performs some tasks and then invokes the callback function. In this case, callbackFunction is the callback function that is passed to doSomething and will be executed when the tasks are complete.

Callback functions with a few detailed code examples.

Example 1: Asynchronous File Reading
In this example, we'll use the fs module in Node.js to read a file asynchronously and use a callback function to handle the result.

const fs = require('fs');

// Define the callback function
function handleFileContent(err, data) {
  if (err) {
    console.error('Error:', err);
  } else {
    console.log('File content:', data);
  }
}

// Read a file asynchronously and pass the callback function
fs.readFile('myfile.txt', 'utf8', handleFileContent);
Enter fullscreen mode Exit fullscreen mode

Here, the readFile function from the fs module reads the content of the file 'myfile.txt' asynchronously. It takes three arguments: the file path, the encoding ('utf8' in this case), and the callback function handleFileContent. When the file reading operation is complete, the callback function is invoked with two parameters: an error object (if an error occurred) and the file content.

Example 2: Timer with Callback
In this example, we'll create a function that uses a callback to execute some code after a specified delay.

function delayedExecution(callback, delay) {
  setTimeout(callback, delay);
}

function callbackFunction() {
  console.log('Callback function executed!');
}

// Execute callbackFunction after a delay of 2 seconds
delayedExecution(callbackFunction, 2000);
Enter fullscreen mode Exit fullscreen mode

Here, the delayedExecution function takes a callback function and a delay time as arguments. It uses the setTimeout function to schedule the execution of the callback function after the specified delay.

Example 3: Array Iteration with Callback
In this example, we'll use a callback function to iterate over an array and perform some operation on each element.

function processArray(array, callback) {
  for (let i = 0; i < array.length; i++) {
    callback(array[i]);
  }
}

function callbackFunction(element) {
  console.log('Element:', element);
}

const numbers = [1, 2, 3, 4, 5];

// Process the numbers array with the callback function
processArray(numbers, callbackFunction);
Enter fullscreen mode Exit fullscreen mode

In this case, the processArray function takes an array and a callback function as arguments. It iterates over each element of the array and invokes the callback function with the current element as an argument. The callback function callbackFunction simply logs the element to the console.

These examples illustrate different scenarios where callback functions are commonly used. Whether it's handling asynchronous operations, scheduling tasks, or iterating over data, callback functions provide a way to specify custom behavior that is executed at a certain point in the code.

Callback functions are commonly used in asynchronous operations such as handling events, making AJAX requests, or working with timers. They allow you to define what should happen after an asynchronous task completes without blocking the execution of other code. This helps in writing more efficient and responsive JavaScript programs.

Top comments (0)