Now let's not store the number that the
passed function does something with inside
test
, but pass it as the
first parameter:
function test(num, func) { // the first parameter is a number
console.log(func(num));
}
Let's use our function:
function test(num, func) {
console.log(func(num));
}
// Shows 4:
test(2, function(num) {
return num * num;
});
For the convenience of our construction:
we have one function test
that takes
a number as a parameter. But what will
happen to the number is not hardcoded in
the test
function.
We can, for example, use the second
parameter of the function test
to pass a squaring function, or we can,
for example, cube function:
function test(num, func) {
console.log(func(num));
}
// Find the square of a number:
test(2, function(num) {
return num * num; // returns a square
});
// Find the cube of a number:
test(2, function(num) {
return num * num * num; // returns a cube
});
Let the function test
take a
number as the first parameter, and
functions as the second and third
parameters that also take numbers.
Let the function test
return
the sum of the results of the
passed functions:
function test(num, func1, func2) {
return func1(num) + func2(num);
}
Invoke the function test
, passing
the number 3
as the first parameter,
the function that squares the number as
the second parameter, and the function
that raises the number to the cube as
the third parameter. Output the result
to the console.