Learn Computing from the Experts | The Rheinwerk Computing Blog

What Are Callback Functions in JavaScript Programming?

Written by Rheinwerk Computing | Feb 12, 2025 2:00:00 PM

The reference to a function in JavaScript can be transferred to another function for internal use.

 

In this context, the transferred function is referred to as the callback function. You can transfer both named functions and anonymous functions as callback functions. Callback functions are also used to handle events in JavaScript programming.

 

In the following program, the output() function is called twice. It’s used to output a regular sequence of values. A mathematical calculation is then carried out for each of these values, the result of which is displayed next to the value.

 

The mathematical calculation can be freely selected. It’s defined in a function, and a reference to this function is transferred to the output() function when it’s called:

  • The first call passes a reference to the named function square(), which returns the square of the transferred value.
  • The second call transfers an anonymous function that returns the reciprocal of the transferred value.

Here’s the program:

 

... <head> ...

   <script>

      function square(x)

      {

         return x * x;

      }

 

      function output(from, to, step, fct)

      {

         for(let p = from; p < to + step / 2.0; p += step)

            document.write(p + " " + fct(p) + "<br>");

         document.write("<br>");

      }

   </script>

</head>

<body><p>

   <script>

      output(5.0, 15.0, 2.5, square);

      output(3.0, 7.0, 1.0, function(p) { return 1 / p; });

   </script></p>

</body></html>

 

The first call calculates the squares of the numbers from 5 to 15 in steps of 2.5, and the second call calculates the reciprocal values of the numbers from 3 to 7 in steps of 1.

 

The output of the program is shown in this figure:

 

 

Editor’s note: This post has been adapted from a section of the book Getting Started with JavaScript by Thomas Theis.