Wasea Wasea - 3 months ago 29
Javascript Question

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

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() {
if (b < 3) {
return b;
} else {
value = myfunction();

Nik Nik
Answer Source

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

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

  return myfunction(local_b);

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download