Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Wed May 24 2023

Callback functions in JavaScript - all you need to know

In this article, we will explain what a callback function is in JavaScript, and also show how we can use them. We will also show cases where you probably already have used them without knowing about it. We will both explore built in functions in JavaScript where callbacks are used, and we will also create our own function where we will use them.

What is a callback function?

A callback function is a function that are passed into another function as an argument, and are then executed from the function it is passed into. Callback functions are widely used in JavaScript, and are a really great way of achieving felxible and reusable code.

Example in built in JavaScript function

We will take a look at some functions you might already have been using where callbacks are used.

Array functions

In below examples, I will share some common functions from Array.prototype where we will use some callbacks.

ForEach

Array.prototype.foreEach() are accepting a callback where we can do what we like with each number. Below example will show how we can pass in two different callbacks for printing even and odd numbers.

const printEvenNumbers = (number) => { if (number % 2 === 0) { console.log(number); } }; const printOddNumbers = (number) => { if (number % 2 > 0) { console.log(number); } }; const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; numbers.forEach(printEvenNumbers); // 2, 4, 6, 8, 10 numbers.forEach(printOddNumbers); // 1, 3, 5, 7, 9

Map

Let's try the map() function as well and see what we can do with it. In below example, we will map each number into a json object with the following attributes: number, doubleValue and halfValue.

const transformToJson = (number) => { return { number: number, doubleValue: number * 2, halfValue: number / 2, }; }; const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const jsonNumbers = numbers.map(transformToJson); console.log(jsonNumbers);

Print

[ { "number": 1, "doubleValue": 2, "halfValue": 0.5 }, { "number": 2, "doubleValue": 4, "halfValue": 1 }, { "number": 3, "doubleValue": 6, "halfValue": 1.5 }, { "number": 4, "doubleValue": 8, "halfValue": 2 }, { "number": 5, "doubleValue": 10, "halfValue": 2.5 }, { "number": 6, "doubleValue": 12, "halfValue": 3 }, { "number": 7, "doubleValue": 14, "halfValue": 3.5 }, { "number": 8, "doubleValue": 16, "halfValue": 4 }, { "number": 9, "doubleValue": 18, "halfValue": 4.5 }, { "number": 10, "doubleValue": 20, "halfValue": 5 } ]

Now we have created a new array from our numbers array with a JSON structure that we used our callback function for.

Create our own functions

Now, we will do some examples where we will apply the callback technique on our own.

Calculator

In below example, we will create a function that will accept two numbers and a callback function. And we will then call our callback function with the numbers provided. We will also create four callback functions with their own logic to handle the numbers with.

const calculateNumbers = (a, b, cb) => { return cb(a, b); }; const divide = (a, b) => a / b; const mulitply = (a, b) => a * b; const add = (a, b) => a + b; const substract = (a, b) => a - b; console.log(calculateNumbers(10, 5, divide)); // 2 console.log(calculateNumbers(10, 5, mulitply)); // 50 console.log(calculateNumbers(10, 5, add)); // 15 console.log(calculateNumbers(10, 5, substract)); // 5

In above example, we created four functions for calculating two numbers, and then called our calculateNumbers with each callback provided.

Logger

In below snippet, we will create a print function which will accept a message and a optional callback function. If the callback is provided, we will call it with the message.

We will then create a callback function that will save all our log messages together with a timestamp that we will print afterwards.

const print = (message, callback) => { console.log(message); if (callback) { callback(message); } }; const messagesPrinted = []; const saveMessage = (message) => { messagesPrinted.push({ message, timestamp: new Date(), }); }; print("Without callback"); print("With callback", saveMessage); print("Without again"); print("With callback again", saveMessage); console.log(messagesPrinted);

Print

[ { "message": "With callback", "timestamp": "2023-05-24T10:22:05.231Z" }, { "message": "With callback again", "timestamp": "2023-05-24T10:22:05.231Z" } ]

Outro

That's it for this guide. Callbacks are extremely common in JavaScript and in frameworks like React etc, and they are really powerful. So if you haven't familiarised yourself with them yet, I strongly suggest you do. If you have any questions or want some other examples or explanations, please reach out here and I'll be happy to assist.

Thanks for reading!

signatureWed May 24 2023
See all our articles