Callbacks

Learn about the callbacks and how we can sort arrays using them.

Introduction to callbacks

A function that’s passed as an argument to another function is known as a callback. The callback can then be called from within the body of the function that it’s an argument of. Being able to call different functions from within functions makes functions even more flexible.

To see an example of this, let’s look at the following function, called bake. This is a JavaScript example of the baking analogy we used for functions earlier. It accepts a string of ingredients as a parameter and then logs some messages to the console.

Press + to interact
function bake(ingredients) {
console.log(`Mix together ${ingredients}...`);
console.log('Bake in the oven...');
}

Try calling the function with an argument like the one in the example below:

Press + to interact
bake('flour, water & sugar');

We can improve this function by adding a callback as a second parameter. This is a function that’s called from within the bake function and allows us to add some extra information. Update the bake function by entering the code below into the console:

Press + to interact
function bake(ingredients, callback) {
console.log(`Mix together ${ingredients}`);
console.log('Bake in the oven');
callback();
}

Overwriting a function declaration: We can overwrite a ...