JS Recursion

Skabe89
2 min readOct 20, 2021

A recursive function is a function that calls itself. Take for example, the following function that is designed to find out if any numbers in an array happen to be odd.

const odd = (arr) => {  //check the length of the array, if empty there are no odd nums  if(arr.length === 0){
return "No Odd Nums"
}
//if the first element in our array is even, remove that element
and run our function on the remainder of the array
else if(arr[0] % 2 === 0){
arr.shift()
return odd(arr)
}
//Odd number has been found else{
return "There is an Odd Num in this array!"
}

The most important part of this function, and something we should always do first with a recursive function is dictate when we will break out of the function. Our first condition in the ‘if’ statement does that for us. If the array is empty it certainly won’t have and odd numbers in it and therefore we will return “No Odd Nums”. Otherwise we will check if the first element in the array is even, if it is we will take away that element and run the same function on the remaining array. This will put our stack in a loop until either one of the elements was found to be odd or we end up with any empty array, and therefore no odd numbers.

Lets take a look at another example of a recursive function, one that sums up all the numbers in a range between 0 and the number.

function sum(num){
if(num === 0){
return 0}
else{
return num + sum(num - 1)
}
}
//sum(2) => 3
//sum(3) => 6
//sum(4) => 10

In our function ‘sum’ we are taking the number and continuously adding that number plus the return of the number minus 1 until we get to 0, when we will then break out of our loop. If not for that first condition in the if statement we would run this until we get an error that read something like ‘Maximum call stack size exceeded’. To better understand this lets visualize how JS is handling this function when we invoke it with an argument of 3.

sum(3)
returns 3 + sum(2)
returns 2 + sum(1)
returns 1 + sum(0)
returns 0

Without our return of 0 we would endlessly call out sum(-1), sum(-2)… until we exceed our stack limit.

sum(3)
returns 3 + sum(2)
returns 2 + sum(1)
returns 1 + 0
sum(3)
returns 3 + sum(2)
returns 2 + 1
sum(3)
returns 3 + 3
sum(3) => 6

Our stack can now clear out once we hit our ‘return 0' to start our chain of returning our sums.

--

--