Intro to Recursion in JavaScript

As I strengthen my JavaScript fundamentals, I am constantly being introduced to different tools and ways to think as a JavaScript developer. I recently have been introduced to recursion and more specifically recursive functions.

On a very basic level, using recursion in programming means the calling a function within itself until a certain condition is reached.

A recursive function must have a condition to stop calling itself. Otherwise, the function is called indefinitely. Once the condition is met, the function stops calling itself. This condition is generally called a base condition.To prevent infinite recursion, you can use and if else statement where one part of the function makes the recursive call, and the other doesn’t. Down below is a very basic example of how recursion works.

function IamRecursion() {
if(base condition) { <====== base condition needed to end recusion
IamRecursion(); <==== function calling itself
else {
// stop calling recursion()

Recursion is helpful to know for technical interviews , but it has some very real world programming uses. A few of these real world situations include delaying timers, for example if you wanted to execute a function multiple times after a set period of time, recursion can be an excellent option. Recursion can also be extremely helpful to use while iterating through a big set of data such as an array and finding a specific element, recursion can make the search more efficient . Recursion also allows for programmers to write DRY code as well as much cleaner code easier for fellow programmers to read.

Happy Coding!

Full-Stack Software Engineer / New York City /