Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript return of recursive function

Hate to open a new question for an extension to the previous one:

function ctest() {
    this.iteration = 0;
    this.func1 = function() {
        var result = func2.call(this, "haha");
        alert(this.iteration + ":" + result);
    }
    var func2 = function(sWord) {
        this.iteration++;
        sWord = sWord + "lol";
        if ( this.iteration < 5 ) {
            func2.call(this, sWord);
        } else {
            return sWord;
        }
    }
}

this returns iteration = 5 but result UNDEFINED ? how is that possible ? i explicitly return sWord. It should have returned "hahalollollollollol" and just for doublecheck, if i alert(sWord) just before the return sWord it displays it correctly.

like image 776
MirrorMirror Avatar asked May 23 '12 12:05

MirrorMirror


3 Answers

You have to return all the way up the stack:

func2.call(this, sWord);

should be:

return func2.call(this, sWord);
like image 166
Quentin Avatar answered Oct 17 '22 03:10

Quentin


You need to return the result of the recursion, or else the method implicitly returns undefined. Try the following:

function ctest() {
this.iteration = 0;
  this.func1 = function() {
    var result = func2.call(this, "haha");
    alert(this.iteration + ":" + result);
  }
  var func2 = function(sWord) {
    this.iteration++;
    sWord = sWord + "lol";
    if ( this.iteration < 5 ) {
        return func2.call(this, sWord);
    } else {
        return sWord;
    }
  }
}
like image 5
Rich O'Kelly Avatar answered Oct 17 '22 02:10

Rich O'Kelly


Your outer function doesn't have a return statement, so it returns undefined.

like image 1
alex Avatar answered Oct 17 '22 03:10

alex