DEV Community

Discussion on: Recursion JS

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

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