Understanding How Recursion works

const countUp = num =>{    console.log(`counting...${num}`);    countUp(num);

Recursion and a Base Case

By passing in an at least one argument which changes with each recursive call we can change the code in the function body itself each time the function calls itself. The key here is the the argument passed in with each recursive call must change in some way with each recursive call. Here’s a simple adjustment to our initial function:

const countUp = num =>{    console.log(`counting...${num}`);    countUp(num + 1); // recursive call
const countUp = num =>{    if ( num === 5) return; // base case        console.log(`counting...${num}`);        countUp(num + 1 ); // recursive call

Order of execution

So far this example isn’t very impressive and only really serves as a replacement of a simple ‘for’ loop, but watch what happens when we move our console.log. Instead of placing our console.log before our recursive call let’s place it after:

const countUp = num =>{    if ( num === 5) return; // base case        countUp(num + 1 ); // recursive call        console.log(`counting...${num}`);
The Execution Stack
const countUp = num =>{
if ( num === 5){ // base case
console.log(`=== Base case reached (see note B)===`);
console.log(`pre-recursive(see note A) - function ${num}`);
countUp(num + 1 ); // recursive call
console.log(`post-recursive(see note C) - function ${num}`);
pre-recursive(see note A) - function 1
pre-recursive(see note A) - function 2
pre-recursive(see note A) - function 3
pre-recursive(see note A) - function 4
=== Base case reached (see note B)===post-recursive(see note C) - function 4
post-recursive(see note C) - function 3
post-recursive(see note C) - function 2
post-recursive(see note C) - function 1
  1. The Base Case
  2. The Order of recursive execution

Software Developer & Armchair Philosopher

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store