I still donât fully understand recursion, but I didnât understand recursion at all until I opened up some recursive code in Chrome Dev Tools.
SO:
Open a new tab in Chrome and enter about:blank in the address bar.
Ctrl+Shift+I opens Dev Tools. Itâll probably open on the Elements tab, so click on the Sources tab.
You should see something like âSnippetsâ and âNew snippetâ. (sry not more detailed but for me this is permanently open in a tab somewhere). Make a new snippet.
This is a fantastic way to test and debug code. Plug this is in there:
Notice âdebuggerâ? Thatâs what allows the magic to happen.
Hit Ctrl+Enter to run the codeâŚokay itâs paused.
Over to the side you should see some controls like a play button, etc. Thereâs a section showing you the current scope, console at the bottom, yadda yadda. Thereâre videos that go into more detail but, for now, just click the button that looks like an arrow pointing at a circle.
What this does is walks through the code one. step. at. a . time. So you can always see whatâs happening.
So whatâs recursion? Itâs a function that calls itself. But I prefer to think of it as a function that recedes into itself, almost as if each function call is itâs own separate room and the program is walking from room to room; this is kinda how it works. If you run that code one step at a time, you might notice a few things.
n is reduced by 1 with each function call. Where are the numbers going? Theyâre getting left behind in each function scope (or âroomâ) for later. Like breadcrumbs. Kinda.
2)The conditional statement if(n < 1) { return []; } is like the final room. Once n < 1 the program picks up an empty array (return []) , turns around, and goes back through each room (function call).
On itâs way back, itâs executing everything in each room. It picks up the n it left behind and puts it in its little box arr.unshift(n); and brings it into the next room return arr; Until itâs done.
Hopefully, this metaphor helps and is not more confusing than it needs to be. Best of luck!