Applying of passing functions as parameters in JavaScript

Let's make a function that will take an array as a parameter, and a function as the second parameter. The passed function will need to be applied to each element of the array:

function test(arr, func) { // returns the modified array }

An implementation:

function test(arr, func) { // Loop starts: for (let i = 0; i < arr.length; i++) { arr[i] = func(arr[i]); // apply the function to each element } return arr; // returns modified array }

Let's apply our function to some array:

function test(arr, func) { for (let i = 0; i < arr.length; i++) { arr[i] = func(arr[i]); } return arr; } // Let's convert an array of numbers into an array of their squares: let result = test( [1, 2, 3], function(num) {return num * num;} ); console.log(result); // shows [1, 4, 9]

Let's make our function call more elegant (it's more common way):

function test(arr, func) { for (let i = 0; i < arr.length; i++) { arr[i] = func(arr[i]); } return arr; } // Let's make the code more elegant: let result = test([1, 2, 3], function(num) { return num * num; }); console.log(result); // shows [1, 4, 9]

Without looking into my code, implement the same function test on your own.

Call the function test you created, passing it an array of numbers as a parameter. Make the function return an array with the cubes of these numbers.

enru