Skip to content

Commit 72f9915

Browse files
authored
Merge pull request #218 from travisallen6/recursion
Added JavaScript_Advance lesson on recursion
2 parents 6f53761 + 7fdc601 commit 72f9915

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

JavaScript_Advance/recursion.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Recursion is when a function calls itself.
2+
// Recursion gives us an interesting way to write algorithms that can solve complicated problems.
3+
4+
// Take for example factorials which is just an integer times each of the integers below it: so 5 factorial (also written 5!) is just 5 * 4 * 3 * 2 * 1.
5+
// If we want to write an algorithm that can calculate the factorial of any given number without using recursion, we could do something like this:
6+
7+
function calcuateFactorialWithoutRecursion(num) {
8+
let total = num;
9+
let nextNumber = num - 1
10+
while(nextNumber >= 1) {
11+
total = total * nextNumber;
12+
nextNumber-- // decrease the next number by 1
13+
}
14+
return total;
15+
}
16+
17+
// calcuateFactorialWithoutRecursion(5) // 120
18+
// 5 * 4 * 3 * 2 * 1 = 120
19+
20+
// We can write the same function this way using recursion:
21+
function calculateFactorialWithRecursion(num) {
22+
if(num === 1) { // This step is critical. The num parameter will keep decreasing until it gets to 1.
23+
// Once the function gets called with 1 as a parameter, the function will return without calling itself.
24+
return num;
25+
}
26+
return num * calculateFactorialWithRecursion(num - 1);
27+
}
28+
29+
calculateFactorialWithRecursion(7) // 5040
30+
// 7 * 6 * 5 * 4 * 3 * 2 * 1 = 5040
31+
32+
// See how clean recursion made this algorithm!

0 commit comments

Comments
 (0)