2

Doing a simple recursive function that calls another function and the scope is off to where it works the first time correctly but the next times it always sets param to undefined.

function log(string){
    console.log(string)
}

function repeat(operation, num, param) {
    if (num <= 0) return
    operation(param)
    return repeat(operation, --num)
}

repeat(log, 5, "hello there")
4
  • par ? normal it doesn't exist Commented Feb 7, 2016 at 1:31
  • What is "par"? That variable appears only once and is never declared or assigned a value. Anyway, the recursive call only passes two arguments, so... Commented Feb 7, 2016 at 1:31
  • 4
    Well, you're not passing any param argument during the recursive call, so yes, it will be undefined... try this return repeat(operation, --num, param) Commented Feb 7, 2016 at 1:31
  • yes this is correct, gracias Commented Feb 7, 2016 at 1:34

4 Answers 4

3

You are not passing the "param" parameter to the recursive calls.

function log(string){
    console.log(string)
}

function repeat(operation, num, param) {
    if (num <= 0) return
    operation(param)
    return repeat(operation, --num, param)
}

repeat(log, 5, "hello there")

should fix it.

Sign up to request clarification or add additional context in comments.

Comments

2

Fix your variable name:

par => param

operation(param)

Comments

1

Are you sure you just didn't want to do this?

function log(string) {
    console.log(string);
}

function repeat(operation, num, param) {
    if (num <= 0) return;
    operation(param);
    return repeat(operation, --num, param);
}

repeat(log, 5, "hello there")

Comments

1

The working code is:

function log(string){
    console.log(string)
}

function repeat(operation, num, param) {
    if (num <= 0) return
    operation(param)
    return repeat(operation, --num, param)
}

repeat(log, 5, "hello there")

When you call the repeat recursively you should provide the 3rd argument - param

diff: return repeat(operation, --num, param) on line 8

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.