Aamir Usmani Aamir Usmani - 10 days ago 6
Javascript Question

Recursion function in Javascript return undefined

function right(a,b){
if( a > b) { console.log(b+1); return b +1 ; }
else
{ right(a +=1,b); console.log(a); }

}


When I call this function it returns undefined.
right(5,10) // undefined. Can anyone one help me why when the variable b is declared and has the value.

Answer

Basically you need to return on the else part something as well.

function right(a,b){ 
    if( a > b) { 
        console.log(b + 1); 
        return b + 1;
    } else {
       console.log(a + 1);
       return right(a + 1, b);
       // ^^^
    } 
}