rafael nextor
rafael nextor

Reputation: 21

javascript recursion return wrong value

There is a piece of recursive function that I was working on and it seems to be returning the wrong value than what is expected. I was able to replicate it and simplify the function into:

function foo(i, target){    
    if(i < target){
        i++;
        foo(i, target);
    }

    return i;   
}
console.log(foo(0,5));

Basically, given the function above, I expect the return value to be 5. However, it seems to return 1. When I did some tracing, I notice that "return i" is being called several times and each time it gets decremented with 1? What's the reason for this behaviour and what can I do to fix it?

Upvotes: 1

Views: 269

Answers (3)

Suren Srapyan
Suren Srapyan

Reputation: 68635

You need also to return form the if part in your code.

function foo(i, target){    
    if(i < target){
        i++;
        return foo(i, target);
    }
   
    console.log(i);
    return i;   
}

console.log(foo(0,5));

Why your code returns 1?

Because it only calls the foo every time while i < target and after it you get all values returned from the nested calls in order 5, 4, 3, 2, 1 and the last one is returned from the first function call is printed. You can check this by putting simple console.log before the return i and compare to the above result.

function foo(i, target){    
    if(i < target){
        i++;
        foo(i, target);
    }
   
    console.log(i);
    return i;   
}

console.log(foo(0,5));

To visualize the returned values you can see

 console.log()                               console.log()
 |   Call with 1                             -- return Call with 1
 |   |   Call with 2                            -- return Call with 2
 |   |   |   Call with 3                           -- return Call with 3
 |   |   |   |   Call with 4                          -- return Call with 4
 |   |   |   |   |   Call with 5        VS               -- return Call with 5  
 |   |   |   |   |   return 5
 |   |   |   |   return 4
 |   |   |   return 3
 |   |   return 2
 |-- return 1

Upvotes: 5

Soolie
Soolie

Reputation: 1820

You have to give return to the recursive function call as well:

return foo(i, target);

function foo(i, target) {
  if (i < target) {
    i++;
    // Change here...
    return foo(i, target);
  }
  return i;
}
console.log(foo(0, 5));

Upvotes: 2

marvel308
marvel308

Reputation: 10458

You are not returning the value of the recursive call

function foo(i, target){    
    if(i < target){
        i++;
        return foo(i, target);
    }

    return i;   
}
console.log(foo(0,5));

Upvotes: 2

Related Questions