Return value of recursive function is 'undefined'

13,166

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.

Share:
13,166

Related videos on Youtube

Hedge
Author by

Hedge

Updated on June 12, 2022

Comments

  • Hedge
    Hedge almost 2 years

    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;
        }
    }
    
    • Ian
      Ian almost 11 years
      No return statement in the if block means undefined. It might be easier to maintain if you put one return statement at the end of the function and set the value to return based on the if statement
    • outis
      outis over 2 years
      Does this answer your question? undefined returned from function
  • Hedge
    Hedge almost 11 years
    I simplified the function as much as possible in order to not distract from the real problem. Thanks a lot.