Returning javascript recursive function

Hate to open a new question to expand 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; } } } 

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

+6
source share
5 answers

You should push the whole stack up:

 func2.call(this, sWord); 

it should be:

 return func2.call(this, sWord); 
+14
source

You need to return the recursion result, otherwise 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; } } } 
+4
source
  func2.call(this, sWord); 

it should be

 return func2.call(this, sWord); 
+1
source

There is no return in your external function, so it returns undefined .

0
source

keep it simple :)

your code modified in JSFiddle

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

Source: https://habr.com/ru/post/916445/


All Articles