12

I need to store the return value in a variable.

I want to know how to fix this code. I know that if the value of b would be 3, I would get value=2, but if the function does more than one iteration I get unidentified. I read that I should use the callback or something but I don't know how, also an explanation of why my code doesn't work and how should I fix it. (Of course this code is for demonstration purpose as if I would show you the original it might get confusing.) Thanks a lot!

var b = 70;

function myfunction() {
    b--;
    if (b < 3) {
        return b;
    } else {
        myfunction();
    }
}
value = myfunction();
console.log(value);
3
  • 7
    Use return myfunction(); in else Commented Nov 4, 2015 at 3:53
  • Thanks a lot! Can you explain how this works, please. Commented Nov 4, 2015 at 3:58
  • 1
    Understanding how recursive functions work Commented Nov 4, 2015 at 4:00

2 Answers 2

7

Your code: myFunction() will return void/undefined on first call, it is not a recursive approach.

Following example is a recursive approach. A recursive function usually receive an argument to be processed and return a final value that bubbles(returned) up to the first caller.

function myfunction(b){
  b--;
  if(b<3) return b;
  else return myFunction(b);
}

When you call a recursive function, you should prepare a test for an escape. Otherwise you might end up in an infinite loop.

Example of an infinite recursive

function badFunction(){
return badFunction();
}
// DON'T call badFunction()

Recursive Example

var b = 70;
var safety = 1000;

function myfunction(local_b) {
  if(safety<0) return;
  safety--;

  // main task
  local_b--;
  
  if (local_b < 3) {
    return local_b;
  }

  return myfunction(local_b);

}
var value = myfunction(b); // when b = 70, value = 2
console.log(value);
document.getElementById('value').innerHTML = value;
<span id="value">_</span>

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

Comments

-1

var b = 70;

function myfunction() {
    b--;
    if (b < 3) {
        return b;
    } else {
        myfunction();
        return b;
    }
}
value = myfunction();
console.log(value);

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.