How to save the return value of a recursive function in a variable JavaScript

27,324

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>

Share:
27,324
Wasea
Author by

Wasea

Updated on November 30, 2020

Comments

  • Wasea
    Wasea over 3 years

    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);