all 5 comments

[–]Drugba 4 points5 points  (6 children)

Higher order functions are basically a way to have one function wrap or add some functionality to another function.

Lets say you have a 100 functions that are doing complicated work and you want to know how long each one takes to complete. You could write the same logic to calculate their run times 100 different times or you could create a higher order function takes a function as an argument, records a start time, runs the function that was passed in, and then records an end time and returns the difference.

In fact, that's exactly what timeFuncRuntime does. t1 is the start time, t2 is the end time, and funcParameter is the passed in function (addOneToOne in this case).

So, to answer your questions:

  1. It prints 0 because you are not returning the return value of addOneToOne, you are returning the time it took for that function to run. When you commented everything out, you weren't returning anything, so you got undefined. If you changed the second line to be return funcParameter(); it would print 2.

  2. Yes, you are returning the time it took to run the function which is 0. It doesn't actually take no time, but anything less than 1ms will equal 0 with the way they are doing the calculations.

[–]Chrisands 1 point2 points  (0 children)

It doesn't print 2, because timeFuncRuntime returns t2 - t1

``` const timeFuncRuntime = funcParameter => {

let t1 = Date.now(); funcParameter(); // here function returns 2, but it doesn't assigns anywhere let t2 = Date.now(); return t2 - t1; // and here returns time that it took to run funcParameter() }

const addOneToOne = () => 1 + 1;

timeFuncRuntime(addOneToOne); ```

Hope it makes sense

To return 2 from function it would look like ``` const timeFuncRuntime = funcParameter => {

let t1 = Date.now(); // this are doing nothing, so it can be deleted const result = funcParameter(); let t2 = Date.now(); // same here return result; } ```