Hello, and welcome! If you’re not a first-time reader, then I’m hoping you have read the previous installment in this series that covered the basics of search algorithms in tree data structures (If not, then you can read part 2 of the previous installment  here, or  here for part 1).

Today I will talk about a programming concept that I find challenging to grasp to this day. That’s right, today we talk about recursion. Recursion is a problem-solving technique in which a given solution (or in our case, function) calls upon itself to be solved. There is a quote by an unknown sage of programming who once said:

“In order to understand recursion, one must understand recursion.”

This quote alone did a lot towards removing the proverbial veil of confusion from my eyes and did for me what it states, literally. With that said, let’s dive right in!

The Recursive Approach

As I mentioned earlier, recursion in programming is a problem-solving approach where a function calls upon itself to solve a given problem. It’s a simply-worded definition, but this programming concept has had my head spinning ever since I first learned about it (until I found that anonymous quote, see above). It’s a problem-solving technique we have used at least once, though you may not recall. If you’ve ever solved a factorial like having to find the value of 5! in school, then you’ve used recursion in your life at least once. Recursion, as a problem-solving pattern, works to call a function inside of the same function’s body. Recursion requires that this be done repetitively, breaking down data to its lowest value, also known as a recursive function’s base case.

Let’s look at a factorial expression (don’t worry, it isn’t complex math). As a reminder, a factorial is the product of all non-zero integers from 1 to _n. _An expression like 5! can be evaluated as 5 * 4 * 3 * 2 * 1, which equates to 120. Let’s build a function that receives a number _n _and returns its factorial value. It’s simpler than it sounds; you can do it!

Though I said that problem solving using recursion is simply calling a function within itself_, _doing so without a way to stop the recursive process would actually cause the call stack (which is of limited size), to overflow when running this function. It goes without saying that this is problematic. We need to establish what is known as a base case, a break condition, so to speak. So long as our recursive callbacks don’t exceed the call stack’s size limit, any returned value in the stack can be used as a base case.

#algorithms #code-newbie #javascript #recursion

JavaScript Data Structures and Algorithms (Recursion, Part 1)
1.30 GEEK