Search code examples
javascriptrecursionreturn

Javascript recursive function returning undefined instead of expected result


I have following function on JSFiddle:

function getRandomPointsInRange(range){

        var x1 = rand(1, 40),
            y1 = rand(1, 40),
            x2 = rand(1, 40),
            y2 = rand(1, 40),
            result;

        if(getDistance(x1, y1, x2, y2) < range){
            console.log('test');
            getRandomPointsInRange(range);
        }else{

            result = {x1: x1, y1: y1, x2: x2, y2: y2};
            console.log(result);
            return result;
        }
    }

It generates two points with distance equal or greater to certain distance (20 in this case). Problem is that sometimes function returns undefined, instead of expected result. You can't see that on JS Fiddle, but console log shows that function returns undefined only when function calls itself at least once (when console.log('test') is triggered. Even when function returns undefined, result itself is actually defined as an object(second console.log shows proper object with points coordinates). Why is that happening and how this can be fixed, so proper object would be always returned?

JS Fiddle link: https://jsfiddle.net/3naLztoa/2/


Solution

  • Prima vista, you need another return.

    Basically recursive functions need at any exit a value if the function should return a value. If you do not specify one, you get by design, undefined.

    To prevent this, you have to return the value of another call of a recursive function.

    function getRandomPointsInRange(range) {
        var x1 = rand(1, 40),
            y1 = rand(1, 40),
            x2 = rand(1, 40),
            y2 = rand(1, 40),
            result;
    
        if (getDistance(x1, y1, x2, y2) < range) {
            console.log('test');
            return getRandomPointsInRange(range);
           // ^^^^
        } else {
            result = {x1: x1, y1: y1, x2: x2, y2: y2};
            console.log(result);
            return result;
        }
    }