top of page

JavaScript Callback Function


ree

In Javascript, Functions are objects. We can pass the objects to functions as parameters. And, also we can pass functions as parameters to other functions and we can call them inside the outer function. This is the situation where we call this process as callback function.

function print(callback) 
{
    callback();
}

The print( ) function takes another function as a parameter and calls it inside. This is valid in JavaScript and we call it a “callback”. So a function that is passed to another function as a parameter is a callback function.


Below are some of the advantages for using Callback Function:

  1. Callback make sure that function is not going to run before a task is completed, it will run when the task is completed.

  2. It helps us to develop asynchronous javascript code and keep safe from error and problems.


Code:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Callbacks</h2>

<p>Adding two given numbers : </p>

<p id="demo"></p>

<script>
function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}

function myCalculator(num1, num2, myCallback) {
  let sum = num1 + num2;
  myCallback(sum);
}

myCalculator(8, 5, myDisplayer);
</script>

</body>
</html>

Source: W3School


Output:


ree


The Tech Platform






4 Comments


Tony
Oct 09

Play Nickelodeon Games online for free and join SpongeBob, Teenage Mutant Ninja Turtles, and more in nonstop fun adventures!

Like

NailArtsy
Oct 09

Discover the latest nail art designs, seasonal trends, tutorials and care tips at https://nailartsy.net/

Like

Tony
Oct 09

Play Disney Games online for free! Discover a world of magic, fun, and adventure with your favorite Disney characters in every game.

Like

jeffreestar
Jul 24

Thanks for the clear code snippet and explanation—definitely a solid that's not my neighbor game intro to callbacks! Looking forward to more JavaScript insights from The Tech Platform!

Like
bottom of page