Member-only story
Understanding How Recursion works

Here’s a function in JavaScript:
const countUp = num =>{ console.log(`counting...${num}`); countUp(num);
}countUp(0);
Given that the function calls itself, we can instantly recognize that this code will cause an infinite loop which will log ‘counting …’ and the current number with each iteration. Yet this very concept — that a function can call itself — sits at the very heart of a recursive function. So what’s the idea here anyway?
Well, it’s important we understand why this code causes an infinite loop. In this case, the function body never changes. This results in the the line of code which calls the function to execute again to always execute. A line such as this is called our recursive call, as it is this line which triggers the function to call itself (and thus which causes this ‘recursion’).
In order to stop an infinite loop we must prevent execution of the line which contains our recursive call so that the function will not call itself again. Obviously we can’t prevent this recursive call if our function body never changes since the function body contains the recursive call. So what’s the solution?
Change the function body.