photo 1527266237111 a4989d028b4b

Thinking about Recursion: How to Recursively Traverse JSON Objects and the Filesystem

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.

man answering two phones

For example:

function printArrayRecursive(arr, i) {
  // base case, stop recurring
  if (i === arr.length){
  // 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++){

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.

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") {
    } else {
      // base case, stop recurring

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()) {
    } else {
      // base case, stop recurring

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?”


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

JavaScript articles for you:
How to Re-render a Vue Route When Path Parameters Change
How To Cache Images – React Native Expo (Managed)
JavaScript With Statement Explained – A Deep Dive

Thanks For Reading!

Follow us on Twitter @q_vault if you have any questions or comments

Take some coding courses on our new platform

Subscribe to our Newsletter for more programming articles

3 thoughts on “Thinking about Recursion: How to Recursively Traverse JSON Objects and the Filesystem”

  1. There is no such thing as a “JSON Object” there is JSON (a UTF-8 string of an encoded value) and there are Objects (in memory representation of properties and values).

    • Well according to the JSON standards

      4. Objects

      An object structure is represented as a pair of curly brackets
      surrounding zero or more name/value pairs (or members). A name is a
      string. A single colon comes after each name, separating the name
      from the value. A single comma separates a value from a following
      name. The names within an object SHOULD be unique.

    • I agree that the vernacular is strange (JavaScript Object Notation Object), but I think its a decent way of describing the entire blob. Perhaps JSON struct? JSON blob? idk hahah

Comments are closed.

%d bloggers like this: