Featured

What Are Callback Functions in JavaScript Programming?

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:

 

Callback Function

 

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

Recommendation

Getting Started with JavaScript
Getting Started with JavaScript

New to programming and JavaScript? Look no further! With this beginner’s guide, learn the language ABCs and start developing applications. Walk through the programming basics: branches, functions, methods, objects, and more. Then create forms and events; use the Document Object Model (DOM); and work with large data sets, processing strings, mathematics, time, and other data structures. Design your web and mobile applications using tools like Ajax, CSS, jQuery, and Onsen UI. Follow code examples and expert tips, and you’ll be developing in no time!

Learn More
Rheinwerk Computing
by Rheinwerk Computing

Rheinwerk Computing is an imprint of Rheinwerk Publishing and publishes books by leading experts in the fields of programming, administration, security, analytics, and more.

Comments