higher order function in javascript

Kaushani RC

I am reading the book Eloquent to learn javascript. I came across this example

function unless(test, then) {
    if (!test) then();
}

function repeat(times, body) {
    for (var i = 0; i < times ; i++) body(i);
}

repeat(3, function (n) {
    unless(n % 2, function () {
        console.log(n, " is even ");
    });
});

// → 0 is even
// → 2 is even

I know functions can be passed as arguments and can be inside one another. But are then() and body() functions? Where are they defined? What's the value of n?

Neta Meta

Here is a little explanation.

function unless ( test , then ) {
  if (! test ) then () ;
}
function repeat ( times , body ) {
  for ( var i = 0; i < times ; i ++) body ( i ) ;
}

// in here you also pass 2 params to repeat.
// 3 and an anonymous function, the function is the argument 'body' in repeat
repeat (3 , function ( n ) {
  // as you can see here - you pass 2 params to unless, 
  // 1 is the result of n %2, and an anonymous  function, the function is the argument
  // "then" in unless.
  unless ( n % 2 , function () {
    console . log (n , " is even ") ;

  }) ;
}) ;

the value of n is changing from 0 to 3 it, its going to be 0,1,2

Also since your a beginner i would suggest using https://jsfiddle.net/ to test stuff out.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related