Thinking about Recursion: How to Recursively Traverse JSON Objects and the Filesystem
Tags: javascript, programming, tutorial, uncategorized
Published: 2019-09-22 14:04:34

---
title: Thinking about Recursion: How to Recursively Traverse JSON Objects and the Filesystem
published: true
tags: Javascript,Programming,Tutorial,Uncategorized
canonical_url: https://qvault.io/2019/09/22/thinking-about-recursion-how-to-recursively-traverse-json-objects-and-the-filesystem/
---

![](https://qvault.io/wp-content/uploads/2019/09/photo-1527266237111-a4989d028b4b-1024x683.jpg)

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.

## What is Recursion?

Recursion is a process in which a **function calls itself**.

![](https://qvault.io/wp-content/uploads/2019/09/cut.jpg)

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:

- Easier to read and understand
- Less memory utilization – _Recursive functions keep all calls on the stack until the base case is reached_
- Faster compute time – _Recursive functions come with the overhead of an entire function call for each step_
- If there is a bug in the recursion, the program is likely to enter an infinite loop

## So Why Use Recursion?

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](https://en.wikipedia.org/wiki/Turing_completeness).

![](https://qvault.io/wp-content/uploads/2019/09/mechanical-turing-machine-in-wood-vo8izckhif0mp4-shot0001_featured.png)<figcaption><a href="https://hackaday.com/2018/03/08/mechanical-wooden-turing-machine/">mechanical turing machine </a></figcaption>

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.

## Examples

**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.

By Lane Wagner [@wagslane](https://twitter.com/wagslane)

Download Qvault: [https://qvault.io](https://qvault.io/)

Star our Github: [https://github.com/q-vault/qvault](https://github.com/q-vault/qvault)

The post [Thinking about Recursion: How to Recursively Traverse JSON Objects and the Filesystem](https://qvault.io/2019/09/22/thinking-about-recursion-how-to-recursively-traverse-json-objects-and-the-filesystem/) appeared first on [Qvault](https://qvault.io).