Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

General Discussion

Josh Keenan
Josh Keenan
19,652 Points

Recursion

So I am a computer science student and have been for a while, but the actual usage of a recursive function does still seem to stump me 3/4s of the time, I understand the concept and can use it in some cases, but in others I might as well not be able to code at all.

Is there any resource anyone knows of that can help me get the hang of it?

1 Answer

Steven Parker
Steven Parker
229,644 Points

There's just a few things to keep in mind when doing recursion:

  • by definition, the function must call itself under some condition(s)
  • there must be some other condition(s) where the function does not call itself
  • it must pass itself a different argument than it started with

For example, Here's a recursive function that adds together all integers up to one you specify:

function sumUpTo(n) {
    if (n == 0) return 0;
    return n + sumUpTo(n-1);
}

So it adds the argument to the result of calling itself with a smaller argument, unless (or until) the argument is 0. This particular task can be easily done without recursion, but it serves as a basic example of how recursion works.