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 trial1 Answer
Alexander Davison
65,469 PointsRecursion is an advanced topic (for beginners), but is also an important concept.
Recursion is where a function calls itself inside the function declaration.
Here's a very simple example of recursion in JavaScript:
function sayHello () {
console.log("Hello!");
sayHello();
}
// This code below activates the infinite streak of "Hello!"s.
sayHello();
If you walk through the code, this is what happens in detail:
- We define the
sayHello()
function. Notice it's calling itself in the function body. - We call the function which activates the code in the function. The
console.log("Hello!")
is called, along with calling itself. - When we call ourselves in the function, it activates the
console.log("Hello")
again and calls itself again. - As you see, it will produce an infinite amount of "Hello!"s (unless you stop the program). Feel free to test this out in the Development Tool's console!
However, above is only a simple example. It's useful when, for example, doing something repetitive. You can also accomplish doing repetitive things with loops, which might be simpler & easier for the computer to handle, but sometimes things are really hard to accomplish with loops and are much easier with recursion.
Let's make two functions that both multiply two numbers together. To do this with recursion, we must notice that multiplying is simply:
- 5 * 5 = 5 * 4 + 5
- 5 * 4 = 5 * 3 + 5
- 5 * 3 = 5 * 2 + 5
- And so on...
Keep in mind that there must be some end point when doing recursion. With multiplication, the end point is when the decreasing number is zero. I'm actually going to list out what the program is going to do under the hood:
- 5 * 5 =
- 5 * 4 + 5 =
- 5 * 3 + 5 + 5 =
- 5 * 2 + 5 + 5 + 5 =
- 5 * 1 + 5 + 5 + 5 + 5 =
- 5 * 0 + 5 + 5 + 5 + 5 + 5 (this is the end point because the number is zero!)
So, we can this program like this:
function multiply(a, b) {
if (b == 0) {
return 0; // This might seem useless, but it's very important!
} else {
return multiply(a, b - 1) + a
}
}
This code works for this case, but for this simple example loops
are easier to use then recursion. Note that loops aren't always easier! :
function multiply(a, b) {
var num = 0;
for (var i = 0; i < b; i++) {
num += a;
}
return num;
}
I hope this helps
~Alex