DEV Community

Grey_W I N D
Grey_W I N D

Posted on

Recursion JS

Please can anyone really explain indepth how recursion works.

Discussion (6)

Collapse
theianjones profile image
Ian Jones

I highly recommend The Little Schemer for an introduction to recursion. It assumes you have no prior knowledge of how recursion works and walks you through simple to pretty complex examples.

Collapse
rusty_xx profile image
Grey_W I N D Author

Thanks man...really appreciate

Collapse
sargalias profile image
Spyros Argalias

Sorry, I can't explain how it works in depth as it's a very large topic, but I'll try to help.

Helpful resource. For starters, I recommend the resource that made it click for me. It's Kyle Simpson's Functional Light JS book, chapter 8. Here is a link to it on his GitHub: github.com/getify/Functional-Light.... Please note that this is somewhat advanced, so there's no need to master everything he talks about in this chapter.

Trace the code. Secondly, I recommend finding some basic examples and literally tracing through the code from n = 0 to n = 3 or so.

const sumRange = n => {
  if (n <= 0) return 0;
  return n + sumRange(n-1);
};

When I was trying to make sense of the weirdness of recursion, I went through functions like that and literally traced the execution of the code. It definitely helped.

Thinking about recursion

Personally, I think about it like it's magic. It just works, because mathematical induction works. I try not to think much more about it.

Next is how I think about the problem I have to solve: What is the result of sumRange(n)? It's just the result of n + whatever the rest of the answer is. What is the rest of the answer? It's the result of sumRange(n-1), so just call that. Also base case is at n=0 where we return 0.

So yeah, think like that and just trust it to work.

Hope that helped a bit. Please feel free to ask any questions.

Collapse
rusty_xx profile image
Grey_W I N D Author

Thank you so much; cause to me recursion works like magic especially when i see posts on stackoverflow using recursion

Collapse
instinct profile image
Instinct

For an indepth view, you should consider the below link:

freecodecamp.org/news/how-recursio...

Collapse
rusty_xx profile image
Grey_W I N D Author

Actually I was looking for an alternative of Array.flat () method.
Then I came across the this recursive solution
developer.mozilla.org/en-US/docs/W...