Suppose we have the function test
that takes another function as a parameter
and print the result of this passed
function to the console:
function test(func) {
console.log( func() );
}
Let the passed function func
take
a number as a parameter and do something
with it. Let's give it, for example, the
number 3
:
function test(func) {
console.log( func(3) );
}
Let's now call the test
function,
passing an anonymous function as a parameter
to it. This anonymous function will take a
number as a parameter and return the square
of that number.
As a result of all this, our construction
will display the square of the number
3
, that is, 9
:
// Shows 9:
test(
function(num) {
return num * num;
}
);
function test(func) {
console.log(func(3));
}
Let's make the code more elegant:
// Shows 9:
test(function(num) {
return num * num;
});
function test(func) {
console.log(func(3));
}
Copy my function test
code.
Invoke this function, passing to it
an anonymous function as a parameter,
which will take a number as a
parameter and return its cube.
Modify your code so that the passed
function is not anonymous, but is
defined as a Function Declaration
with the name func
.
Change the passed function to a Function
Expression with the same name func
.
Let the passed function now take two
parameters and return their sum. When
calling the passed function inside
test
, pass the number 2
and the number 3
to the passed
function. Print the result with alert.