Recursion is a key concept in coding. Gavin explains it simply here.
💬 Chat with this Video
Ask anything about this video…
⏱ Full Transcript — click any timestamp to jump
So, what is recursion? Think of it like standing between two mirrors. You see the image repeating smaller and smaller each time. Recursion is when a function calls itself potentially several times to solve a problem. Let's look at a basic practical code example in JavaScript where recursion is used to solve a problem. In this case, the problem is calculating factorials. So, what is a factorial? A factorial is a way of multiplying a whole number by all the positive integers below it. So, what is the factorial of three? We can calculate the result like this: 3 * 2 * 1, which equals to 6. The factorial of 3 is 6. What is the factorial of 5? We can calculate the result like this: 5 * 4 * 3 * 2 * 1, which equals 120. The factorial of 5 is 120. You can see that this pattern of logic is repeating until the final multiplication operation involves multiplication by the value of 1. This alludes to the base case. And when the base case is true, the pattern of logic needs to stop repeating. So, this is where the final result is calculated, and we no longer want to continue calling the recursive function. So, the recursive reusable function to calculate factorials looks like this. The function calls itself until the base case is true, i.e., when n equals to 1. The final result is returned after the result is multiplied by 1. So, the function keeps calling itself until it hits a base case, the stopping point. Remember, no base case equals to infinite loop. So, that's recursion, breaking big problems into smaller versions of themselves.
Generated algorithmically for Search Engine
Indexing.