1

I've created a working recursive for loop, but it only works if my callback has no arguments. I've tried callback(arguments) and callback(...arguments).

Thanks for any help you can provide!

function loopFunc (numOfSteps, callback) {
    let i = 0;

    if (i >= numOfSteps) {
        let i = 0
        return
    } 
    callback()
    loopFunc(numOfSteps - 1, callback)`enter code here`
}

It works if the callback takes no arguments:

function noArgsHello() {
    console.log('hello')
}

const thisWorks = loopFunc(3, noArgsHello);
thisWorks()

It doesn't work if the callback takes an argument:

function sayHello (input) {
    console.log(input)
}

const thisDoesntWork = loopFunc(3, sayHello('hello');
thisDoesntWork()
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
  • 1
    Possible duplicate of [Javascript callback function with parameters](https://stackoverflow.com/questions/13003828/javascript-callback-function-with-parameters) – Sebastian Simon Dec 27 '18 at 02:31
  • `callback` should be a `function` object, not `function` execution result (if the result is not a function object). `const thisDoesntWork = loopFunc(3, function(){sayHello('hello');}); thisDoesntWork();`should work. – Alex Kudryashev Dec 27 '18 at 02:37

3 Answers3

0

You almost there! It depends what is your goal here, you can use either option:

function loopFunc (numOfSteps, callback) {
let i = 0;

  if (i >= numOfSteps) {
      let i = 0
      return
  }

 callback(numOfSteps)
 loopFunc(numOfSteps - 1, callback);
}

function printExtraStuff(greeting) {
  return (val) => { console.log('greeting ', val)}
}

function printSteps(num) {
    console.log(num);
}

var test1 = function() { loopFunc(3, printExtraStuff('hi there') )};
test1()

var test2 = function() { loopFunc(3, printSteps )};
test2()
Uma
  • 836
  • 5
  • 7
0

In this way:

const thisDoesntWork = loopFunc(3, sayHello('hello');

You are not passing a callback anymore, but you are executing the sayHello function and passing the returned value of that function to the loopFunc.

What you can do in these cases, is to use the bind method of functions for passing the function with arguments:

const thisDoesntWork = loopFunc(3, sayHello.bind(sayHello, 'hello'));

Or you can pass directly a function which executes your sayHello so that the argument is still a function and it will be used as callback inside your loopFunc:

const thisDoesntWork = loopFunc(3, () => sayHello('hello'));

quirimmo
  • 9,800
  • 3
  • 30
  • 45
0

You need to use an anonymous function if you want to pass parameters in an argument -based function (callback is an argument). Your code should instead be like this:

function sayHello(input) {
  console.log(input)
}

const works = () => sayHello('hello'); 
works();
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79