JavaScript callback functions

6 August 2022

Functions exist in most programming languages and are an important aspect of JavaScript. A function is a block of code which performs a specific task defined by the programmer. Using functions allows us to avoid writing the same code multiple times to do the same task.

In JavaScript a function is an object which means we can pass it as an argument to another function. This concept is known as a callback function.

Regular JavaScript function

To explain this, lets first define a regular function in JavaScript called getTime which prints the current time to the console.

function getTime() {
    var date = new Date();
    console.log(date.getHours() + ':' + date.getMinutes() + ":" + date.getSeconds());
}
getTime();
Output
10:15:24

Callback function

Now that the getTime() function is defined we can pass it as an argument to other functions to be used as a callback. As an example of this we’ll use the setTimeout() function which takes two arguments: a function and a time delay in milliseconds.

function getTime() {
    var date = new Date();
    console.log(date.getHours() + ':' + date.getMinutes() + ":" + date.getSeconds());
}
getTime();
setTimeout(getTime, 5000);
Output
10:18:24
10:18:29

After running this snippet, you should see two times outputted, the time when getTime() is called for the first time and then, 5 seconds later, the time when getTime() is called from the setTimeout() function.

Anonymous function

Another type of function that is often used in JavaScript is the anonymous function. An anonymous function is a function without a name and is defined within another function.

Here we’ll define a function within the setTimeout() function which has the same definition as the getTime() function, but doesn’t have a name.

setTimeout(function() {
    var date = new Date();
    console.log(date.getHours() + ':' + date.getMinutes() + ":" + date.getSeconds());
}, 5000);
Output
10:24:53

Callback arrow function

In modern JavaScript, it is also common to use arrow functions as callback functions. An arrow function is similar to an anonymous function, but it is written using the => syntax. To use this snippet as an arrow function, we can remove the keyword function and add in the arrow between the empty argument brackets and the opening function body bracket.

setTimeout(() => {
    var date = new Date();
    console.log(date.getHours() + ':' + date.getMinutes() + ":" + date.getSeconds());
}, 5000);

Arrow functions are widely used in JavaScript so it’s good to know what they look like and how to use them.

In the next few posts we’ll be using other inbuilt JavaScript functions with arrow functions to manipulate different types of data.