JavaScript knowledge - Callback functions explained

3-5 min read Depositphotos_305450184_l-2015.jpg

Quite a few junior developers asked me lately what is a callback function and how can it be used in javascript so in this article I will try to give an easy and clear understanding of what a callback function is and show some relevant coding examples.

So, let's get started ... :)

What is a callback function? A callback function is a function that can be passed to other function as an argument and then called in that other function when needed in order to achieve a specific result or complete a certain action.

Practical example

function showCarFeatures(type, color) {
  console.log(`Type of the ${color} car is ${type}`);
}

function car(type, color, callback) {
  callback(type, color);
}

car("BMW", "blue", showCarFeatures);
car("Audi", "grey", showCarFeatures);

In the above example we pass the showCarFeatures callback function to car function as third argument and then we invoke it providing the first two arguments type and color.

Using function expression instead of function declaration, template literals and the awesome ES6 arrow function syntax the code is shorter and more clear:

const showCarFeatures = (type, color) => console.log(`Type of the ${color} car is ${type}`);

const car = (type, color, callback) => callback(type, color);

car("BMW", "blue", showCarFeatures);
car("Audi", "grey", showCarFeatures);

Instead of declaring the callback function we could use an anonymous function as the third argument in car function:

function car(type, color, callback) {
  callback(type, color);
}

car("BMW", "blue", function(type, color) {
  console.log(`Type of the ${color} car is ${type}`);
});

or using function expression and ES6 arrow function:

const car = (type, color, callback) => callback(type, color);

car("BMW", "blue", (type, color) => console.log(`Type of the ${color} car is ${type}`));

If you got to the end it means that you found the article interesting and hopefully useful. Thank you for reading.

More reliable links related to callback functions: