Higher-Order Functions - Functions as Parameters

Hi guys,

I stuck in the Higher-Order Functions - Functions as Parameters module. Can anyone explain me step by step the following piece of code? Thank you in advance.

const timeFuncRuntime = funcParameter => {
let t1 = Date.now();
funcParameter();
let t2 = Date.now();
return t2 - t1;
}

const addOneToOne = () => 1 + 1;

timeFuncRuntime(addOneToOne);

timeFuncRuntime(() => {
for (let i = 10; i>0; i–){
console.log(i);
}
});

Hello @justynasieczka. I will use a slightly different example, as I don’t think this example is very good:

const timeFuncRuntime = funcParameter => {//declares a function which
//accepts one argument-a function
let t1 = Date.now();//sets t1 to the date/time it is declared
funcParameter();//calls the parameter provided to the function-which is
//a function
let t2 = Date.now();//sets t2 to the date/time it is declared
return t2 - t1;//return t2-t1
};

const addOneToOne = () => console.log(1 + 1);//declares a function which logs
//2 to the console

timeFuncRuntime(addOneToOne);//this calls the first function "timeFuncRuntime
//with the function called "addOneToOne"-which prints `2` to the console
//Output can be seen in dropdown labelled 1

timeFuncRuntime(() => {//this again calls the first function defined-
//timeFuncRuntime with a function that is created inside the parameter
//see dropdown 2 for an elaboration on this 
for (let i = 10; i>0; i--){//the function which is created when timeFuncRuntime
//is called loops through numbers 10-1
console.log(i);//this prints the current value of `i`, which is declared 
//in the function which is the argument for 'timeFuncRuntime'. In dropdown 3
//is the result
}
});
1

This will log:

2
2

Because the timeFuncRuntime function accepts a function as its argument, you can create a function as you call the function. It is similar to calling this function with 3 instead of var_equals_3:

function someFun(arg){
  console.log(arg);
}

let var_equals_three = 3;
someFun(var_equals_three);//prints 3
someFun(3);//also prints three

In the same way I called the someFun with both a variable and integer as an argument, you can call a function (timeFuncRuntime) that accepts a function as its argument(aFunc) with both a pre-declared function, and a function that is declared only when you call someFuncRuntime.
I hope this was helpful!

3

This will log:

10
9
8
7
6
5
4
3
2
1

I hope this helps!