Home > Net >  Understanding higher order JavaScript functions
Understanding higher order JavaScript functions

Time:10-27

I am learning Higher-order functions from Eloquent JavaScript, I did my research for a similar question but was unable to find it. There was a similar question related to mine from the same topic and same chapter but it was a basic one. Here's the link for a similar one: Higher-order functions in Javascript.

I am facing a problem with the below code:

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

let unless = (test, then) => {
  if(!test)then();
};

repeat(3, n => {
  unless(n%2 == 1, () => {
    console.log(`${n} is even`);
  });
});

// Output:
/  → 0 is even
// → 2 is even
  1. How does this higher-order function work?
  2. How does the looping work in order to determine whether the number is even or odd?

CodePudding user response:

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

n is the number of time you want execute the action function.

the action function is called here a callback function

if you do repeat(5, console.log) you gonna have:

0
1
2
3
4

you can also execute another function like this

repeat(5, item => console.log(item));

CodePudding user response:

Higher-order functions either accept a function as a parameter, or return a function; both unless and repeat accept functions as parameters.

repeat accepts a number and a function, and simply calls whatever function was passed to it, that number of times.

unless accepts a value and a function; if the value is falsy then the function will be called.

What this demonstrates is that functions can be passed around just like any other variable: inside repeat(), action refers to the function itself, and action() calls that function to get its result.

CodePudding user response:

In general, ur unless function sounds like - take the condition, test it, then run the callback. The repeat func sounds like run action(s) n times. The result sounds like run action(s), and check inside if it satisfies the condition, then run unless function.

  • Related