JavaScript Callback Functions How-To, With Examples

JavaScript Callbacks

This article will explain callback functions in JavaScript – what they are, why they’re used, and how to use them.

What is a Callback in the JavaScript Programming Language?

callback function is a function that is passed as a parameter to another function to be executed from within the second function.

What are Callbacks Useful For?

Callback functions are usually used to execute a function when another has been completed. This allows for easy code- reuse.

A single function that accepts a callback can be used multiple times for different tasks by passing a different callback.

For example, you may have a function that processes a number called processNumber(). It should execute one of two functions depending on whether the number being processed is odd or even. Those functions can be provided as callback functions to processNumber() and executed from within it, rather than duplicating their code.

Callback functions are commonly used to chain functions together so that one completes after the other. Thus, it is generally assumed that a callback function is always executed when a function has completed all other tasks.

Where are Callback Functions Used?

Callback functions are used in built-in JavaScript functions as well as in many libraries available online. You can also write your own functions to accept callbacks.

They are a useful tool and worth getting to know.

Example

Below I’ll illustrate the example used above – by passing multiple callbacks to a function to remove code duplication and allow for the chaining of functions.

// Define a function to process even numbers, to be called from the processNumber() function
function processEvenNumber(num){
    console.log("Number " + num + " is even!");
}

// Define a function to process odd numbers, to be called from the processNumber() function
function processOddNumber(num){
    console.log("Number " + num + " is odd!");   
}

// Define the function which will call either of the two above functions as callbacks
function processNumber(num, oddCallbackFunction, evenCallbackFunction){

    console.log("Processing number!");

    // Decide if num is odd or even using the % operator to get the remainder when num is divided by 2 - if the remainder is 0, it is even
    if(num % 2 == 0){
        // The callback function should be called using the name it is given as a parameter (evenCallbackFunction in this case) NOT the name the function was given when it was defined (processEvenNumber)
        evenCallbackFunction(num);
    } else {
        oddCallbackFunction(num);
    }

}

// Define an array (list) of numbers to test with
var testNumbers = [3, 6, 7, 9, 1, 2];

// Loop through testNumbers and run processNumber() on each of the numbers
testNumbers.forEach(function(num){

    // run processNumber() on each number in the testNumbers array
    processNumber(num, processOddNumber, processEvenNumber)

});

So What’s Going on Here?

First, two functions are defined: processing even and odd numbers (processEvenNumber, and processOddNumber). Each accepts a single parameter (the number) and prints it along with a bit of text about whether it was deemed odd or even. These two functions will be used as callback functions later.

The processNumber function is then defined. It accepts 3 parameters – the number to process, as well as two callback functions. It will check if a number is odd/even and then call the relevant callback function by the name it was given as a parameter.

A forEach() loop is then used to loop through an array of test numbers.

Two callbacks have been used for this example – you can use as few or as many callbacks as you like.

This example doesn’t really illustrate a reduction in code as short functions are used to demonstrate – however it’s easy to see that if the functions were longer, there would be a significant reduction in the amount of code written.

Still confused? You can find out more about JavaScript callback functions here.

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published. Required fields are marked *