Callback functions in JavaScript

Functions can be passed as parameters to other functions. Such function-parameter is called callback. Let's see how they work with an example.

Suppose we want to make a function that will take an array as the first parameter, and a callback as the second, which will be applied to each element of the array:

function each(arr, callback) { // here is some code }

Let's write the implementation of our function:

function each(arr, callback) { let result = []; for (let elem of arr) { result.push( callback(elem) ); // invokes the callback function } return result; }

Our function each is universal. This means that we can pass different callbacks to it, performing different operations on arrays. In this case, the code of our function will remain unchanged - only the passed callbacks will change.

For example, let's use our function to square each element of an array. To do this, we will pass the corresponding callback as a parameter:

let result = each([1, 2, 3, 4, 5], function(num) { return num ** 2; }); console.log(result);

And now let's raise the elements of the array to a cube. To do this, we will pass another callback that performs this operation as a parameter:

let result = each([1, 2, 3, 4, 5], function(num) { return num ** 3; }); console.log(result);

Given an array of numbers. Use the each function we created to double each element.

Given an array with strings. Use the each function we created to flip the characters of each string in reverse order.

Given an array with strings. Use the each function we created to capitalize the first character of each string.

Nuances

Callbacks don't have to be anonymous functions. For example, let's say we have the following function:

function square(num) { return num ** 2; }

Let's use it to square each element of the array:

function square(num) { return num * num; } let result = each([1, 2, 3, 4, 5], square); console.log(result);

Use the following function to cube all the elements of an array:

function cube(num) { return num ** 3; }
enru