Effective Javascript debugging: Recursion

Joao Santos
3 min readJul 14, 2019

It’s easy nowadays on the web to find tricks and guides on debugging javascript. But do you know when to apply which technique? It’s not enough to know what tricks and APIs are out there, you have to know what situations each tool is best suited for. In this a series of posts I will show you some examples of difficult issues (performance, memory leaks, race conditions, bugs) and how one might approach the debugging process.

Debugging deeply recursive algorithms

Let’s say you have a tree of data that you want to iterate over and aggregate data from.

It could look something like this:

However, what if for some reason the end result is not what you expect? What do you do? Assuming the issue is not an exception (that would be by far the easiest scenario) you could:

  • Step through with the debugger. But the function is called so often and the error could be hundreds of calls deep into the recursion making this very impractical.
  • Add logs. This is promising and for small datasets this will be enough but if those spit out thousands of lines it can be quite difficult to spot the error especially if, unlike in our simple example, being able to reason about the order of execution is key

So what do you do?

In case the result is something completely unexpected like undefined, null, NaN when it should be something that is defined you can use conditional breakpoints to track the exact moment when the result becomes invalid

In case the result is just wrong but not completely unexpected like 34 when it should be 57 the approach I would use is: Recursive nested logs!

One of the many cool things the console api of javascript is capable of doing is group logs using console.group or groupCollapsed, but this also allows to group, groups of logs too! With this you can recreate the iteration structure in your logs and be able to be very verbose with your logs without burying the truth in a sea of text

Important: If you are debugging node.js in the terminal or using a your IDE to debug your page nested logs will likely not show up correctly! My personal recommendation is chrome’s inspector (can debug node.js too) but this will work with all major browser debuggers

Regular logs:

Order of operation is very unclear and logs are potentially miles long

Nested logs:

As you can see in the nested logs, they have the exact same tree structure as your data, giving you a clear visual indication of input, operations and output and allowing you to open the path of the tree that you care about by following the unexpected results and not confusing about what is happening on what node. All that needed to be done to get these logs is:

It’s not any harder to do than regular logs and it won’t clog the console no matter how complex the data.

I hope you liked the first post of effective javascript debugging. Please leave feedback as to what can be improved!

--

--