Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value of recursive function is 'undefined'

Tags:

Whenever I execute this snippet the console.log before return returns the array with 20 times the value 23. However console.log(Check(users, 0, 20)); returns only 'undefined'.

What am I doing wrong?

var users = [23, 23, 23, 23, 23, 23, 23, 23, 23, 23]; console.log(Check(users, 0, 20));  function Check(ids, counter, limit){     ids.push(23);      // Recursion     if (counter+1 < limit){         Check(ids, counter+1, limit);     }     else {         console.log(ids);         return ids;     } } 
like image 600
Hedge Avatar asked Jul 08 '13 13:07

Hedge


1 Answers

You forgot to return a result from the point, where you entering recusrion.

var users = [23, 23, 23, 23, 23, 23, 23, 23, 23, 23]; console.log(Check(users, 0, 20));  function Check(ids, counter, limit){     ids.push(23);      // Recursion     if (counter+1 < limit){         return Check(ids, counter+1, limit); // return here!     }     else {         console.log(ids);         return ids;     } }  

But return value seems useless, cause' your function altering initial array as well.

like image 137
Olegas Avatar answered Sep 26 '22 10:09

Olegas