Skip to content
Advertisement

Learn Javascript : Higher Order Function

anyone can explain this code..? especially “action(i)” in for scope. i’m new in JS

function repeat(n,action){
    for(let i= 1; i<=n; i++){
        action(i);
    }
}

repeat(10, console.log);
repeat(3, alert);

Advertisement

Answer

Higher order function are functions that take other functions as parameter(s). It is based on functions being so-called first-class-members in Javascript, which says, among other things, this: functions can be passed to other functions, as parameters.

In your example the passed function inside the repeatfunction is called action, which is defined by your repeat function signature (n,action) (regardless of any name the actual function that is being passed in might already have), so whatever function gets passed into repeat is callable inside it using action().

Please note that there is no way to guarantee that the actual call will have a function as a second parameter; noone can prevent somebody from making calls like repeat('foo', 'bar') or even repeat(). It is your job as a developer to make your function failsafe in this regard, or to take the shit in, shit out standpoint.

A more simplified example would be this:

function showMessage(message, showMethod) {
  showMethod(message);
}

showMessage('Hello world shown by console.log', console.log);

showMessage('Hello world shown by alert', alert);

showMessage('Hello world shown by console.error', console.error);
  • showMessage is a function that shows a message, which it expects to be the first parameter when it is called.
  • The actual function that should be used to display the passed message needs to be passed into showMessage as a second parameter.
  • When called, showMessage runs the function that was passed as a second parameter (which is renamed to showMethod inside showMessage), passing message to it.

Another more practical use case could be this:

function add(x, y) { return x + y; }
function subtract(x, y) { return x - y; }
function multiply(x, y) { return x * y; }
function divide(x, y) { return x / y; }

function calculate(x, y, calcFunction) { 
  const result = calcFunction(x, y);
  return result;  
}

console.log(calculate(2, 5, add));
console.log(calculate(2, 5, subtract));
console.log(calculate(2, 5, multiply));
console.log(calculate(2, 5, divide));
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement