FAQ: Higher-Order Functions - Functions as Parameters

Thanks so much for your reply. First, Why use an “anonymous” function? Why not call it something?
Second, What does HOF mean? And third, why the => ? The only place I have seen this is when you create a function e.g.

const doThis = () =>{
}

Did I miss something in the lesson before? It’s almost like they skipped some major definitions. The cheat sheet doesn’t even address this.

Thank you again for your help. I really do appreciate it.

1 Like

Really kind of you to volunteer!

1 Like

So it is transient and disposable. We only need it to exist within the context of the current process. Not always the case, such as when we give it a name in an assignment, but we can make the name re-assignable, so the function is still disposable.

Higher Order Function

It’s the relaxed syntax to replace the function keyword, but also to impose a function expression. It’s a wound down version of the behavior of typical functions, sans this, arguments, &c. The relaxed syntax is the real plus, but should be confined to simple expressions.

If the function is more complex, then the vanilla function would be preferred, though one wonders about the gains from not having the headroom of a standard function (this, arguments, &c.).

One of the biggest pluses of arrow functions is implicit returns.

function isAlpha(s) {

}
const isAlpha = function (s) {

}

or,

const isAlpha = s => ! s.split('').some(x => /[^a-zA-Z]/.test(x))

console.log(isAlpha('abcdefg7'))    //  false
console.log(isAlpha('abcdefgh'))    //  true

This is an anonymous function we likely don’t need anywhere else in our program…

x => /[^a-zA-Z]/.test(x)

It serves its purpose in place, otherwise we don’t need it cluttering up the namespace.

But if we decided we did need it,

const nonAlpha = x => /[^a-zA-Z]/.test(x);

And then later,

const isAlpha = s => ! s.split('').some(nonAlpha)

It would become the callback of our isAlpha() function via the .some() method… That is HOF working seamlessly with very little use of intermediate variables, or even program steps. The net aim is to reduce our code to expressions, and little else. When we merge this with a functional environment they carry the whole load.


m = 1
b = 1
y = x => m * x + b

There is no mystery here that y will always be one more than x and it will be a straight line when graphed that passes through y = 1 on the y-axis.when x = 0 on the x-axis.

m and b are allowed to be scoped variables above the function. Given the written context it is no surprise. This allows both variables to be dynamic but in the scope of the function, proper, and still have a direct input. Functions as traditionally written would still allow this, but not as explicitly. Arrow functions really took us around a corner if we look at it from an old school perspective. We, of all people will be the ones to discover their weaknesses but the spec is clear on those anyway, so what of our complaints? They are unfounded.

I’m a bit confused why I can’t use shorthand for the if else statement. When I type this, I get an error:

Code firstTry === secondTry ? return firstTry : return ‘This function returned inconsistent results’;

should be: return condition ? true : false, this way, you don’t have to repeat the return keyword

2 Likes

Hi everyone, please can someone do a walkthrough of the exercise for the 3rd lesson of High- Order- functions, the second task, I am totally stuck, the whole description is quite clear to me but the explanation of the tasks seem to be very confusing: 2.

Write a higher-order function, checkConsistentOutput() . This function should have two parameters: a function and a value. It should call the argument function with the value two times. If the callback function produces the same result twice, it should return the result of the function call, otherwise, it should return the string 'This function returned inconsistent results'

const checkConsistentOutput = (func, val) => {

let firstTry = func(val);

let secondTry = func(val);

if (firstTry === secondTry) {

    return firstTry

} else {

    return 'This function returned inconsistent results'

}

};

Can someone help me understand why the val in firstTry and secondTry are enclosed in (), but only separated by comma in const checkConsistentOutput = (func, val) => { ?

Thanks!

They are the arguments in the call(s) to func().

We pass in a function reference and a value for that function to evaluate.

This was the first exercise of this course that I struggled to understand. (I’ve got almost zero CS background).

I’ve worked it out now, but the instructors may be able to reduce future confusion with the right feedback.
The real point of confusion for me was that the purpose of the code I was being asked to write wasn’t clear:

The first instruction was:
"This function should have two parameters: a function and a value. It should call the argument function with the value two times. If the callback function produces the same result twice, it should return the result of the function call, otherwise, it should return the string 'This function returned inconsistent results'"

Later the instruction is this:
"Write a higher-order function, checkConsistentOutput() . This function should have two parameters: a function and a value. It should call the argument function with the value two times. If the callback function produces the same result twice, it should return the result of the function call, otherwise, it should return the string 'This function returned inconsistent results'"

If the hint was about how to interpret the question it would’ve been more useful:
eg: “your function should evaluate another function by running it twice with the same variable to confirm that it returns a consistent result.”
The plain English explanation of the purpose of the code was missing, so I was flailing around aimlessly. Once I understood what I was supposed to be achieving, the code itself was very simple.

Since this is the first point of confusion I’ve had in the course though, overall I’m incredibly impressed. I wish my own field had such well structured learning environments and helpful culture!

could someone please tell me where I went wrong in this code?

I somewhat understand higher functions. . But what is the point of passing addOnetoOne() to this function?
let t1 and let t2 record the date then, you subtract t2 - t1 to get the difference. What is the point of adding 1+1 inbetween?

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

Next, In the following code the lesson mentions anonymous functions…

In this example, we invoked timeFuncRuntime() with an anonymous function that counts backwards from 10. Anonymous functions can be arguments too!

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

What is a loop counting down from 10 going to do with the timeFuncRuntime() function? is this just to show that anonymous functions can be passed as arguments? Maybe I’m not understanding anonymous functions.

timeFuncRuntime calculates how long it takes for a function to execute/run. So now we can calculate execution time of any function we want. Isn’t that nice? :slight_smile:

just an example of Anonymous function

1 Like

Hello

Could someone help me? I don’t know where my code is wrong? The error said, line 21 Syntax error but I don’t see any error. Also a part of the question I don’t understand ’ If the callback function produces the same result twice, it should return the result of the function call, otherwise, it should return the string 'This function returned inconsistent results'’ . I got the below code from Hint but I don’t understand well about this question? Could someone advise me?
thanks

const time2p2= timeFuncRuntime (checkThatTwoPlusTwoEqualsFourAMillionTimes);

const checkConsistentOutput = (function, value) => {
  let first = function(value);
  let second = function (value);
  if (first === second) { 
    return first;
  } else { 
 return 'This function returned inconsistent results';
  }
};

here:

const checkConsistentOutput = (function, value) => {

function is a reserved keyword in JavaScript, so you can’t use this keyword as parameter name

1 Like

Thank you stetima94.
Now I didn’t know I cannot use function (keyword) as the parameter name. Now i changed func but could you please explain what is the question meant? 'If the callback function produces the same result twice, it should return the result of the function call, otherwise, it should return the string 'This function returned inconsistent results' ’.

in return, it is called ‘first’, can I call ‘second’ too?

My code is below :

const checkConsistentOutput = (func, val) => {
let first = func(val);
let second = func(val);
if (first === second) {
return first;
} else {
return ‘This function returned inconsistent results’;
}
};

yes, you could return second too. Give you have determined the outcomes are the same

1 Like