JavaScript Allonge: Code Snippet

function repeat( num, fn ){
  return (num > 0) ? (repeat(num - 1, fn), fn(num)) : undefined
}

repeat(3, function(n){
  console.log("Hello " + n)
})
 //=>
    'Hello 1'
    'Hello 2'
    'Hello 3'

I’m trying to go through this code line by line but I’m confused as to what’s going on with:
(repeat(num - 1, fn), fn(num)) after the function is invoked with both arguments passed.

Is it invoking repeat(num,fn) recursively? How does fn(num) play a role in this?

If you wrote it like this, it becomes clearer.

function repeat( num, fn ) {
  if (num > 0) {
    repeat(num - 1, fn);
    return fn(num);
  }
  else {
    return undefined;
  }
}
1 Like

@kevcomedia Much clearer. Thank you :slight_smile: