DEV Community


Given a choice, would you choose an iterative approach or a recursive one?

myterminal profile image Mohammed Ismail Ansari ・1 min read

It's beautiful how the same problem can be solved using an iterative or a recursive algorithm, both having their own advantages and disadvantages. Personally, I first got familiarized with looping structures and was fairly comfortable thinking that way (I imagine it's the same for most of us back when we started). My first encounter with recursion was a scary one (I was specifically made to fear it) and it took me a couple of years to actually try it myself and get comfortable with the concept and then it did not take much time to fascinate me.

Having watched quite a lot of lectures from SICP on YouTube a few years back (still did not get through the entire list), and having used them in most of my implementations at work and in my personal projects, I still like recursive algorithms. Furthermore, concepts like tail recursion make it even interesting.

However, I read an awesome post recently and it talked about so many disadvantages of using recursion, most of which I do agree with myself. There were a few comments about that recursive vs iterative thing, but I just wanted to ask to the community, for if you had a choice, what would you rather go with: an iterative approach that is easier to understand (as most of our minds are trained that way) or a recursive approach (that feels very functional)?

Discussion (3)

Editor guide
khalyomede profile image
Khalyomede • Edited

I do not use recursive often, like really not that much.

The only time I used it is when I found myself creating this old NodeJS package to "inline" codes imported in a file (using ES6 import syntax" down to the main file).

In this case, I needed to get an AST of the file, and, whenever I encountered an import "foo", I would get the AST of this file, and in this sub file, whenever I encountered an import "bar", I would get the AST of this file, and...

You got the idea 😂

So I guess recursivity made sense in this case because this was natural to think of a fractal way to solve this.

Else, I would do some sequential algorithm to solve my problems, which would eventually requires iterating.

myterminal profile image
Mohammed Ismail Ansari Author

I'd definitely agree with you on that: it all depends upon the requirement for which one's more appropriate for that specific use-case. For me, in most cases, I get the hint within seconds of looking at the problem.

xxzozaxx profile image
Ahmed Khaled

I would like to go recursive