DEV Community

Cover image for Reframing recursive functions
Jemma
Jemma

Posted on

Reframing recursive functions

I’ve been learning about recursive functions lately (functions that call themselves), and at first they felt pretty overwhelming. Trying to keep track of what happens in the first call, then the second, third, and so on — plus figuring out which values get passed where and when the arithmetic happens — felt confusing.
For a while, I really struggled with even simple recursive problems because I kept trying to hold everything in my head at once, and it just wasn’t working. After experimenting with different approaches, I finally found a method that helps me make sense of recursion. If you’re finding recursion tricky too, I hope these tips are useful.
Think of each recursive call as creating a new stack frame.
Just like any normal function call, each recursive call gets its own space in memory. Draw a little box for each call and write down the variables and their values for that frame.
Remember that none of the stack frames disappear until the base case is reached.
Every call waits for the next one to return before it can finish. This follows the exact same rules as any other function — nothing magical or different is happening.
At the end of the day, recursive functions behave like normal functions.
The name might make them feel intimidating, but the underlying mechanics are familiar. If you carefully track each stack frame as calls are made, recursion becomes much easier to reason about.
Good luck, and don’t give up on recursion — once it clicks, it becomes a really powerful tool!

Top comments (0)