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);
Tushar
  • 85,780
  • 21
  • 159
  • 179
Wasea
  • 187
  • 1
  • 1
  • 7

2 Answers2

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>
Nik
  • 709
  • 4
  • 22
-1

var b = 70;

function myfunction() {
    b--;
    if (b < 3) {
        return b;
    } else {
        myfunction();
        return b;
    }
}
value = myfunction();
console.log(value);
DarkAjax
  • 15,955
  • 11
  • 53
  • 65
SF_bs
  • 1
  • 1