Saturday, March 30, 2024

Explain JavaScript Callbacks?

 A callback is a function passed as an argument to another function.

In the below example, we can see we are passing displayValue function as an argument to doSum function while calling doSum function.

doSum(2, 3, displayValue);

function displayValue(sum) {

  console.log('callback function called');

  console.log('Sum is '+sum);

}

function doSum(num1, num2, sampleCallbackDemonstration) {

  let sum = num1 + num2;

  sampleCallbackDemonstration(sum);

}

Output:

callback function called

Sum is 5

Note: When you pass a function as an argument, remember not to use parenthesis.

When to Use a Callback?

They above example is to understand the callback syntax.

Where callbacks really shine are in asynchronous functions, where one function has to wait for another function like waiting for a file to load.

In the real world, callbacks are most often used with asynchronous functions.

A typical example is JavaScript setTimeout().

setTimeout(myFunction, 3000);

function myFunction() {

  // some code here

}

In the example above, myFunction is used as a callback.

myFunction is passed to setTimeout() as an argument.

3000 is the number of milliseconds before time-out, so myFunction() will be called after 3 seconds.

With asynchronous programming, JavaScript programs can start long-running tasks, and continue running other tasks in parallel. But, asynchronus programmes are difficult to write and difficult to debug.Because of this, most modern asynchronous JavaScript methods don't use callbacks. Instead, in JavaScript, asynchronous programming is solved using Promises instead.

No comments:

Post a Comment