What is recursion? (JS Series)
Recursion is a function that calls itself. The function that it calls is named a recursive function. So, what if it ends up in an infinite loop? Don’t worry, it has an exit condition. You can think of recursion as the mathematical factoring process, it’s repeating the process of taking out a factor over and over again until you are left with prime numbers.
Recursion is used for sorting algorithms, parsing XML/HTML and working with files in a directory structure. All algorithms using recursion can be refactored with an iteration instead of using recursion. In some languages, such as C++ and Java, iterations are preferred over recursions. Overall, recursion is a clever way to solve problems. The best way to understand recursions is using factorials. Remember that 8! = 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 40320 is the same as 8! = 8 x 7! = 40320 Using a concept called the base case, we work backwards to find the answer. Below we have an example coded in Python. Take a moment to follow along the code to cement this confusing topic long-term!
Resources: