|
1 | 1 | # Understanding Recursion in JavaScript |
2 | 2 |
|
3 | | -The ability for something to be defined in terms of itself is called recursion. |
4 | | -Recursive functions are functions that call themselves. |
| 3 | +Recursion is a powerful concept in programming that involves a function calling itself. |
| 4 | +It can be a bit tricky to grasp at first, but once you understand the fundamentals, it becomes a valuable tool in solving complex problems. |
| 5 | +We'll explore recursion in JavaScript with easy-to-understand examples. |
5 | 6 |
|
6 | | -Suppose that you have a function called `recurse`. |
7 | | -This function is recursive if it calls itself inside its body, like this: |
| 7 | +## What is Recursion? |
8 | 8 |
|
9 | | -```js |
10 | | -function recurse() { |
11 | | - // ... |
12 | | - recurse(); |
13 | | - // ... |
14 | | -} |
15 | | -``` |
| 9 | +Recursion occurs when a function calls itself, either directly or indirectly. |
| 10 | +It's similar to a loop, but it involves breaking a problem down into smaller, more manageable sub-problems. |
16 | 11 |
|
17 | | -A recursive function usually has a condition to stop calling itself and return a value, known as a _base case_. |
18 | | -If a base case is missing, in most cases, because it will call itself indefinitely, it would be able to run forever. |
19 | | -In reality, in most of those situations, you'll end up with a "StackSize error": an error raised by the runtime because the _stack_ of function calls has grown beyond a predefined limit because each recursive call adds to this _stack_ until it returns (and it doesn't). |
20 | | -The message of this error is `Maximum call stack size exceeded`. |
21 | | - |
22 | | -```js |
23 | | -function recurse() { |
24 | | - if (baseCondition) { |
25 | | - // stop calling itself |
26 | | - //... |
27 | | - } else { |
28 | | - recurse(); |
29 | | - } |
30 | | -} |
31 | | -``` |
| 12 | +### Example 1: Countdown |
32 | 13 |
|
33 | | -Recursive functions often can be used instead of `for` loops for more succinct code. |
34 | | -For example, take a countdown. |
35 | | -Here's the more intuitive `for` loop approach: |
| 14 | +Let's start with a simple example: a countdown function. |
36 | 15 |
|
37 | | -```js |
38 | | -function countDown(fromNumber) { |
39 | | - for (let i = fromNumber; i > 0; i--) { |
40 | | - console.log(i); |
| 16 | +```javascript |
| 17 | +function countdown(num) { |
| 18 | + // Base case |
| 19 | + if (num <= 0) { |
| 20 | + console.log('Blastoff!'); |
| 21 | + return; |
41 | 22 | } |
| 23 | + |
| 24 | + // Recursive case |
| 25 | + console.log(num); |
| 26 | + countdown(num - 1); |
42 | 27 | } |
43 | 28 |
|
44 | | -countDown(3); // 3, 2, 1 in separate lines |
| 29 | +// Call the function |
| 30 | +countdown(5); |
45 | 31 | ``` |
46 | 32 |
|
47 | | -We could solve this using recursion too: |
| 33 | +In this example: |
48 | 34 |
|
49 | | -```js |
50 | | -function countDown(fromNumber) { |
51 | | - console.log(fromNumber); |
52 | | - if (fromNumber > 1) { |
53 | | - countDown(fromNumber - 1); |
| 35 | +- **Base case**: When `num` becomes less than or equal to 0, the function prints "Blastoff!" and stops calling itself. |
| 36 | +- **Recursive case**: The function prints the current `num` and calls itself with `num - 1`. |
| 37 | + |
| 38 | +### Example 2: Factorial |
| 39 | + |
| 40 | +Now, let's look at a classic example of recursion: calculating the factorial of a number. |
| 41 | + |
| 42 | +```javascript |
| 43 | +function factorial(n) { |
| 44 | + // Base case |
| 45 | + if (n === 0 || n === 1) { |
| 46 | + return 1; |
54 | 47 | } |
| 48 | + |
| 49 | + // Recursive case |
| 50 | + return n * factorial(n - 1); |
55 | 51 | } |
56 | 52 |
|
57 | | -countDown(3); // same result |
| 53 | +// Test the function |
| 54 | +console.log(factorial(5)); // Output: 120 |
58 | 55 | ``` |
59 | 56 |
|
60 | | -Here, our base case is when `fromNumber` is 1, in which case we don't call `countDown` again. |
| 57 | +In this example: |
61 | 58 |
|
62 | | -Apart from just displaying numbers, recursive functions can be used for more complicated procedures, such as keeping a sum or total. |
| 59 | +- **Base case**: When `n` is 0 or 1, the function returns 1. |
| 60 | +- **Recursive case**: The function multiplies `n` by the factorial of `n - 1`. |
63 | 61 |
|
64 | | -```js |
65 | | -function sum(n) { |
66 | | - if (n <= 1) { |
67 | | - return n; |
68 | | - } |
69 | | - return n + sum(n - 1); |
70 | | -} |
| 62 | +## Key Concepts |
| 63 | + |
| 64 | +### Base Case |
| 65 | + |
| 66 | +Every recursive function should have at least one base case, a condition where the function stops calling itself. |
| 67 | +Without a base case, the recursion would continue indefinitely, leading to a stack overflow. |
| 68 | + |
| 69 | +### Recursive Case |
| 70 | + |
| 71 | +The recursive case defines how the function calls itself with a smaller or simpler version of the problem. |
| 72 | + |
| 73 | +## Pros and Cons of Recursion |
| 74 | + |
| 75 | +**Pros:** |
| 76 | + |
| 77 | +- Elegant solution for certain problems. |
| 78 | +- Mimics the mathematical induction concept. |
| 79 | + |
| 80 | +**Cons:** |
| 81 | + |
| 82 | +- Can be less efficient than iterative solutions. |
| 83 | +- May lead to stack overflow for deep recursion. |
| 84 | + |
| 85 | +## Conclusion |
| 86 | + |
| 87 | +Recursion is a valuable technique that simplifies complex problems by breaking them into smaller, more manageable sub-problems. |
| 88 | +Understanding base cases and recursive cases is crucial for implementing effective recursive solutions in JavaScript. |
| 89 | + |
| 90 | +**Learn More:** |
71 | 91 |
|
72 | | -sum(3); // 6 |
73 | | -``` |
| 92 | +- [MDN: Recursion in JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#recursion) |
| 93 | +- [Eloquent JavaScript: Chapter 3 - Functions](https://eloquentjavascript.net/03_functions.html) |
0 commit comments