Skip to content

Write a JavaScript code to add two numbers using the call back function

  • by

Generally, callback function not required for addition operation but it could use to show the result. Call the Addition (addNumber) function with a callback, and let the Addition (addNumber) function run the callback after the calculation is finished:

JavaScript code to add two numbers using call back function example

HTML example code:

If you want to execute a function right after the return of some other function, then callbacks can be used.

<!DOCTYPE html>
<html>
<body>
    <p id="demo"></p>

    <script>

        function result(value) {

            console.log("Call Back Funciton")
            document.getElementById("demo").innerHTML = value;
        }

        function addNumbers(num1, num2, callBackFunction) {
          let sum = num1 + num2;

          callBackFunction(sum);
      }

      // Test case  
      addNumbers(15, 15, result);

  </script>
</body>
</html>

Output:

Write a JavaScript code to add two numbers using the call back function

Note: Remember not to use parenthesis at passing a function as an argument.

Right: myCalculator(5, 5, result);

Wrong: myCalculator(5, 5, result());

Do comment if you have any doubts and suggestion on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading