Advanced JavaScript Debugging

Advanced Debugging Techniques in JavaScript – Part 1

by on January 6, 2014 1:36 pm

Introduction

I was a terrible debugger when I first started programming. I could tell an issue was happening, but it always took me a long time to track down where and why it was happening. Even in a strongly-typed language like C++, it took me hours to find simple bugs in my code.

Debugging is one of the hardest parts of being a programmer. There are as many classes and books on programming as stars in the sky, but next to nothing on formal debugging. When an issue occurs, it could be in code you’ve written, code someone else has written, code another company has written, an issue in the user’s browser, a network hiccup, or any other number of issues. Figuring out where and why something is broken takes time even for the best programmers.

I’ve been writing code for a long time, and have picked up some tricks along the way. In this blog series, I’ll go over some strategies I use to diagnose and fix bugs. Some techniques and strategies I discuss are specific to JavaScript while others can be applied to any programming language.

Validating Assumptions

All of the techniques I will discuss are different flavors of the same idea: validate your assumptions.

As I said before, I was a terrible debugger when I first started programming. It was in my third programming class in high school that I started to really ask myself why debugging was so hard. I made a conscious effort to analyze and dissect the things I was doing to fix my bugs. A pattern emerged after a while. I found that I was spending much more time than I needed to on peripheral issues than trying to address the issue itself. My effectiveness increased tremendously when I would first identify my assumptions then formulate how they could be validated.

The best way to focus on the issue itself is to validate your assumptions. Lets say a user has reported that clicking an Add button isn’t bringing up the Add form. A list of assumptions immediately comes to mind:

  1. A controller bound the Add button’s click event to a method.
  2. The method will open up the Add form when executed.
  3. The Add form will open up correctly when told to do so.

Each assumption should then be validated. If it turns out the assumption is valid, then the bug more than likely isn’t there. If it is invalid, then the bug is more than likely there. Some ways to validate the assumption are:

  1. Ensure that the method is actually getting called on click.
  2. Make sure the click event is spelled correctly.
  3. Check that the event is bound to the correct method.
  4. Test other click listeners to be sure they’re getting called.
  5. Is the Add form able to actually open?

Debugging an Enterprise-level application can be a ting task. There are so many different files and classes that it can be overwhelming to debug something like the issue above. The best part about validating assumptions is that it is actionable and concise. It limits the scope to just what is relevant, and provides real tests that can be ran to identify a problem quickly. Its effectiveness is only limited to how well the assumptions are defined, and how direct the validations are.

There’s no real trick to figuring out what the assumptions are. It’s something that takes time and practice. There are, however, several different techniques I use to validate my assumptions.

Binary Search

Most people, even if they aren’t programmers, use binary searches on a regular basis. When someone guesses a number and is given feedback of “higher” or “lower,” they are using a binary search to narrow down the solution. The idea behind a binary search is simple: split a data set into two, and find which half contains what you’re looking for.

The same concept can be applied to debugging. Assume I have a really long, complicated method that produces a bug. I need to find out where in the method the bug starts occurring. Rather than checking each and every line, I comment out the second half of the method. If the bug no longer happens, then I know it must be caused by something I commented out. I then comment out the first half, uncomment out the second half, and comment out the last fourth. If it still happens, I know the issue is in the beginning of the second half. This process can be repeated until the culprit line or expression is found. Imagine how much time would have been wasted had the first half been checked line by line. It may have yielded some results, but since the bug was in the second half there’s no reason to really consider the first.

The binary search technique is one that can be applied to any language. One disadvantage is that it makes the naive assumption that all methods are modular enough to run one section and produce the same result. There are often cases where a variable in the first half is used in the second half, so completely commenting out the first half isn’t an option. Binary search still allows large chunks of code to be ignored to find the root cause.

debugger Statement

Setting breakpoints to get the current call stack and local/global variable is a cornerstone to any debugging utility. JavaScript debuggers do allow breakpoints to be set when inspecting code. Most people, however, don’t know about the debugger statement.

The debugger statement allows you to define breakpoints as part of the code itself. If the same line needed to be inspected in multiple different browsers, it’s easier to put a debugger statement in the code than try to set the breakpoint in each individual developer tools.

To put a debugger statement in JavaScript code, simply do:

debugger;

I use debugger statements for a wide variety of uses. If I’m working on coding and need to setup stub methods to fill in later, I’ll add a debugger statement to remind myself to fill it in. I also don’t put white space to the left of those kind of debugging lines to make it easy to spot and correct before I check my code in to source control.

I’ve noted several times that the debugger statement is a statement, not an expression. This is because I’ve often seen people write:

if (this.someMethod() && this.someOtherMethod() && debugger && this.someOtherOtherMethod())

They want to see the call stack after someOtherMethod is executed, but don’t want to step through each previous method. The line above is invalid JavaScript syntax, and will throw a run-time exception. The valid version of the code uses an automatically executed closure:

if (this.someMethod() && this.someOtherMethod() && (function(){debugger;})() && this.someOtherOtherMethod())

It looks funky to non-JavaScript programmers, but it works.

I prefer debugger statements to setting breakpoints in the browser’s developer tools. If you set a breakpoint in a file in Chrome and it is loaded asynchronously, it will throw a breakpoint at the end of the file once it is loaded. This gets very annoying if you’ve put breakpoints in multiple files. Debugger statements don’t suffer this behavior. They also make it easier to compare behavior in two browsers at the same time.

Overview

In this blog, I’ve gone over the paradigm I use when debugging. I also discussed binary searching, which can be used in any language. The debugger statement allows for quicker debugging between browsers. In the next blog, I will go over top-down, bottom-up, and event listener breakpoints. These are slightly more advanced than the previous techniques, but are critical to effectively debugging complex JavaScript application.

— Zach Gardner, asktheteam@keyholesoftware.com

Advanced JavaScript Debugging Series:

  • Part 1 – Validate Your Assumptions, Binary Search, and the debugger statement
  • Part 2 – Bottom-Up debugging, Top-Down debugging, and Break on DOM changes
  • Part 3 – Chrome-specific debugging techniques
  • Part 4 – Coming Soon – how teams that use Agile can help their developers and QAs debug JavaScript effectively
  • Share:

7 Responses to “Advanced Debugging Techniques in JavaScript – Part 1”

  1. Silon says:

    I was expecting something on debugging, and was disappointed to find the article was just a load of newbie crap.

    • Keyhole Software says:

      Hi Silon,

      There are many who don’t understand the fundamentals of debugging. This post was a foundation that the rest of the techniques will build off of – Part 2 will have more JavaScript-specific techniques, planned to be published February 10th. Thanks for reading.

  2. […] my previous post on advanced debugging techniques in JavaScript, I spelled out the idea of validating assumptions. This is the most important concept when it comes […]

  3. […] is the third part in my series on Advanced Debugging Techniques in JavaScript. Part 1 introduced Validate Your Assumptions, Binary Search, and the debugger statement. Part 2 covered […]

  4. […] This was originally published in the Keyhole Software blog on 1/6/2014. […]

  5. […] I got to May 1st, 2014. The bug occurred in this version, but not in the April 1st, 2014 version. Using the same principle to my Binary Search JavaScript debugging technique, I tried the April 15th, 2014 version. The bug did not occur, so I know it was somewhere between […]

Leave a Reply

Things Twitter is Talking About
  • Doing #Agile with a Distributed and/or Remote Team? No Problem! Tools and techniques for success - http://t.co/XrYJE8Xict
    July 6, 2015 at 12:35 PM
  • New to #JavaScript prototypal inheritance? Here are some notes to help you along the way - http://t.co/NTIDZS6Uhy
    July 5, 2015 at 7:55 AM
  • ICYMI: we've released a demo version of #GrokOla which is open to the public. Try out its features & capabilities - http://t.co/O4ladowmFU
    July 4, 2015 at 3:05 PM
  • Happy 4th of July from the Keyhole team! We hope that you have a happy and safe holiday with your family and friends.
    July 4, 2015 at 9:55 AM
  • Let's talk testing. Here are common challenges #Agile teams face when writing automated tests & how to overcome them: http://t.co/DrKbNZJcE0
    July 3, 2015 at 11:06 AM
  • #GrokOla users get free educational tutorials. But lucky you, we've released some to the public. #JavaScript primer - http://t.co/nIR9XiWY6O
    July 3, 2015 at 10:55 AM
  • Being able to isolate debugging techniques can help make you a better debugger. Here's Time-Oriented #Debugging http://t.co/UplJgP4VzC
    July 2, 2015 at 10:50 AM
  • RT @zachagardner: @zachagardner has declared it is @ChipotleTweets day at @KeyholeSoftware . You have been warned 🐓🐖🐄
    July 2, 2015 at 10:09 AM
  • Current state of random number generation & the differences in how #Java & #JavaScript approach it - http://t.co/5tBKNXnu8T #security
    July 1, 2015 at 2:45 PM
  • Woohoo - 600 followers! Thanks, everyone. We'd love to ask you - what type of tweets / dev content would you like to see more of from us?
    July 1, 2015 at 10:38 AM
  • We would like to welcome Dallas Monson to the team today! Dallas is a Senior Architect focused on UI/UX and #JavaScript. Welcome, Dallas!
    July 1, 2015 at 8:35 AM
  • Good introduction to TypeScript - http://t.co/0N22fVpAHt Plus, how to approach modularization in #TypeScript - http://t.co/wxRWGBj3Uh
    June 30, 2015 at 3:25 PM
  • .@mrbristopher just delivered a new S911 Night Drone to James Hayes, winner of our #kcdc15 giveaway! Congrats, James! http://t.co/RriJIxubH2
    June 30, 2015 at 11:35 AM
  • It feels like primitives could have been left out of the initial implementation of #Java. See why - http://t.co/A8ChCBHXJO
    June 29, 2015 at 4:05 PM
  • Developers in a bounce house! I repeat, developers in a bounce house! We had a blast at our 1st company picnic. Pics: http://t.co/XIqs7ECUst
    June 29, 2015 at 1:40 PM
  • New #SpringBatch tutorial from @jhackett01: Spring Batch – Replacing XML Job Configuration With JavaConfig http://t.co/PmdXnriKQu #java
    June 29, 2015 at 11:46 AM
  • We had such a fun time at the Keyhole company picnic! Pictures to come, including some of our developers in the bounce house. #loveourteam
    June 29, 2015 at 8:41 AM
  • In #JavaScript, how do we harness the power of callbacks without the confusing mess of nested functions? Promises - http://t.co/j1gAJ9hi3D
    June 29, 2015 at 8:40 AM
  • .@zachagardner We are so happy that your family attended! This will definitely need to be repeated every year!
    June 28, 2015 at 8:14 PM
  • Thank you to all on the Keyhole team who came to our first inaugural company picnic! Wonderful food, family and bounce house fun!
    June 28, 2015 at 7:50 PM