DEV Community

Cover image for Recursion Post Recursion Post
MikeDudolevitch
MikeDudolevitch

Posted on

Recursion Post Recursion Post

In the time since graduating from Flatiron School's software engineering program, I've been looking for ways to shore up my knowledge and expand on the concepts taught in the course. Free Code Camp's curriculum has been awesome for that- little bite sized mini-Labs that you have to solve before moving onward. In going through those tests as a study review, I did run into a concept in Javascript programming that I wasn't familiar enough with: recursion.

I mostly knew recursion as being a pitfall for beginner developers that forgot to close a loop, or set a condition going the wrong direction so as to continue forever. Ctrl-C was my way to escape her siren clutches before melting my computer's processor from the inside out. But it turns out it can be harnessed to solve Javascript problems with some clean and easily readable code.

const recursiveFunction = (n) => {
    if (n == 0) {
       console.log("This is the base case")
    } else {
       console.log(n)
       recursiveFunction(n - 1)
    }
}
Enter fullscreen mode Exit fullscreen mode

Above is a fairly basic function using recursion to countdown from whatever number is provided as an argument when invoked. Programmatically, it works similarly to a for loop, going through each case, operating on it (in this case console logging the present number) and then decrementing it and doing likewise until the loop is done. But the setup is a little different in recursion: you're gonna start with a 'if' statement, that will represent your base case- ie. the condition that will stop it from calling itself endlessly. In our case that's the passed in number reaching 0, and it console logs and never calls again. Boom, our function did what we wanted it to do, and we don't have so smash Ctrl-C.

The 'else' statement is where we operate, calling the very same function within our defined function, only with the passed in number being decremented by 1 in our case- or otherwise operating on that argument so we call it again and again until we hit that base case.

Free Code Camp has a very in-depth look at the concept in terms of using them in your algorithms- I highly recommend taking a deeper dive than my primer on the subject if you're like me and would like to add this to your problem solving arsenal: https://www.freecodecamp.org/news/understanding-recursion-in-programming/

Top comments (0)