21

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;
    }
}
2
  • 2
    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 Commented Jul 8, 2013 at 14:05
  • Does this answer your question? undefined returned from function Commented Oct 14, 2021 at 14:51

1 Answer 1

44

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I simplified the function as much as possible in order to not distract from the real problem. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.