I work primarily on application-level programs, so I tend to not use recursion very often. However, every now and then I need a function that is best solved recursively. It is important to be able to recognize when a problem is best solved recursively, and to be able to write it when the time comes.
Recursion is a process in which a function calls itself.
For example:
function printArrayRecursive(arr, i) {
// base case, stop recurring
if (i === arr.length){
return;
}
console.log(arr[i])
// call ourself with the next index
recursive(arr, i+1)
}
In the code above, printArrayRecursive prints one element from the list, then calls itself again with the next index. Each successive call to itself prints the next element, and so on. The recursion continues until the base case is reached. In our example, the base case is when the index is equal to the array's length.
The same function looks quite a bit different in the iterative world, which you are probably more familiar with:
function printArrayIterative(arr){
for (let i = 0; i < arr.length; i++){
console.log(arr[i])
}
}
In the case of simply printing the items of a list, the iterative approach is better for a number of reasons:
All iterative programs can be written using recursion, and all recursive programs can be written using iteration. This is because both systems are, unless limited by the implementation, turing complete.
mechanical turing machine
The primary reason to choose recursion over iteration is simplicity.
Many years ago many compilers and interpreters didn't support the syntax for iteration. For-loops simply didn't exist. This is because it is much simpler to write an interpreter that can handle recursion, than it is to write one that supports loops.
Likewise, even if a compiler does support loops, some problems are simpler to solve with a recursive function. A good example is tree-traversal. I often find myself writing recursive functions to find every property of an arbitrary JSON object, or looking through every file in a folder that can have an infinite number of nested subfolders.
Recursively print all properties of a JSON object:
function printAllVals(obj) {
for (let k in obj) {
if (typeof obj[k] === "object") {
printAllVals(obj[k])
} else {
// base case, stop recurring
console.log(obj[k]);
}
}
}
}
Recursively print all the filenames of a folder, and its subfolders, and their subfolders, ad infinitum.
function printSubFiles(dir) {
files = fs.readdirSync(dir);
files.forEach(function (file) {
absName = `${dir}/${file}`
if (fs.statSync(absName).isDirectory()) {
printSubFiles(absName)
} else {
// base case, stop recurring
console.log(file)
}
});
};
When trying to figure out how to write a function recursively, think,
"What is my base case?" or in other words, "What should stop the recursion from continuing?"
Once that is hammered out, the rest of the function just needs to answer the questions,
"What do I want to do with my current value?"
and
"How do I call myself to get to the next value?"
Recursion is an important principle to understand for any programmer, and I hope this helps you be just a little better! Thanks for reading.
Previously published at https://qvault.io/2019/09/22/thinking-about-recursion-how-to-recursively-traverse-json-objects-and-the-filesystem/
Download Qvault: https://qvault.io
Star our Github: https://github.com/q-vault/qvault