Home > Software design >  Higher-order function in JavaScript
Higher-order function in JavaScript

Time:08-19

I got this code when learning about "higher-order function" in JS. I can not figure out how the parameter "m" in this code would be run from 0-5? I understand how the function action(i) is called n times, but which part of this code give the action(i) value from 0 to (n-1)? Thank you.

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

function test(condition, result) {  
  if (condition) result();  
}  

repeat(6, m => test(m % 2 == 0, () => {  
    console.log(m);  
    } 
)  
)

CodePudding user response:

I assume this is just confusing for the sake of being confusing, but let me have a try...

repeat gets passed 6 and a function that will accept a number as the argument. The function passed into repeat is test. Test gets passed in a condition and a function (result). Repeat runs 6 times and calls test each time, passing the i in repeat to the m in test. Each time test is run, it checks if m is even, and if so, runs the result function, which is passed in as a callback and just console.logs the value of m.

No matter what number is passed into repeat, m starts at 0 (from i in the for loop). This will print every even number up to, but not including the number passed in.

  • Related