What are Recursive Functions?

Jackson Beytebiere
3 min readOct 19, 2020

One day I encountered a tricky problem. Given an array, return a new array so that it is only one level deep. Meaning that the given array could have an array within it or and array within an array within an array and so on, also known as a nested array. I needed to write a function that would flatten out an array in Javascript without using the built in method Array.prototype.flat( ).

My first thought was to iterate over the provided array, and if the current element in the iteration was not an array I would push that into my current array. But if that element was an array, I could throw the element into a while loop and then check if that element within the array was an array and if not go one level deeper, or something like that. But what if there were multiple elements within the nested array? What if there was a nested array within the nested array that had multiple elements? I was stumped and walked away from my computer to contemplate. I thought there has to be some way to do this without a dozen iterations and 100 lines of code. After calming my mind, I decided to investigated as to how I could solve this problem in a concise manner and came upon a concept known as recursion.

https://xkcd.com/ https://creativecommons.org/licenses/by-nc/2.5/

What is recursion? Recursive’s definition as far as computing goes is:

relating to or involving a program or routine of which a part requires the application of the whole, so that its explicit interpretation requires in general many successive executions.

-Oxford Languages

A real world example of recursion could be an island that has a lake with a volcano in the middle and within that volcano crater is a lake with an island. There is such a lake in the Philippines known as Taal Lake .Recursion with functions means that the function will involve calling upon itself repeatedly until a condition is met.

Getty Images

With recursion in mind, I wrote out my function. First I iterate through the array, and then check if its element is an array, and if not I shove it into my new array. If it is an array, I feed that element back into my function and iterate over that array element.

Recursion is a powerful tool to have in your mental tool box. Next time you have a big problem, see if you can split that problem into smaller problems and solve them piece by piece. That is the basic concept of recursion.

--

--

Jackson Beytebiere

I write about programming and specifically CSS | HTML | JavaScript | Ruby | React.js | Redux.