What exactly are Recursions?!

For some reason im not able to get a good understanding of how we use recursions. Seeing all the stuff calling itself makes me dizzy. :woozy_face:

Why recursion over loops in some cases?
Also, is there an easy way to picture how to use it.
I know its calling a function itself until it something is satified or done.

Recursion is confusing.

Recursive functions are relying on the base case. For some specific input function will return concrete result - this is the base case. Otherwise function will be calling itself, with input changed slightly, that’s eventually should reach the input returning the base case.

When recursive function ends up with some kind of “maximum”, “recursion” or “stack” error usually it means that the base case was incorrect and function went into kind-of infinite loop with calling itself, instead of eventually reaching base case.

Visualizing can be indeed helpful with it, for seeing how exactly function is executed tool like this can be used: JavaScript Tutor - Visualize JavaScript code execution to learn JavaScript online

There’s many resources about recursion, I found this video to clear up some things for me. Code there is using python, but on a concept level that’s irrelevant: 6. Recursion and Dictionaries - YouTube

1 Like

The truth is that often using a loop (iterative solution) is better than recursion. That is even true for a lot of the recursion teaching examples. There is no problem that you can solve with recursion that can’t be solved without. For for certain data structures (like trees, graphs, linked lists, etc.) the recursive solution is much easier and more readable. And recursion sometimes shows up on interviews so it is great to know. But really, in about 9 years of professional programming, I’ve only written 2. But there are probably some types of coding where they deal with them every day. There are definitely problems where the recursive solution is waaaaaaay simpler.

Why recursion over loops in some cases?

I think this takes time and work. For me, it was when I understood what the call stack was doing that helped. Look up some videos - some visualization might help.

But also don’t stress out about it. Don’t worry about becoming an expert in recursion. Just kind of get a feel for the basics and maybe keep coming back to it as a side project.


And if you look bak through the forum, there are a lot o discussion about this - this confuses a lot of people. I know that I’ve explained it a few times.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.