Wallaby.js Blog
Integrated Continuous Testing Tool for JavaScript

JavaScript backdoor debugging

Sometimes I put “console.log” in my JavaScript code just to inspect some latest object values in some deeply nested scopes of my application. Quite often I realise that one “console.log” isn’t enough, so I add more, and so forth. Occasionally I need to modify some objects in the code that I’m tracing on the fly, right from the console, but I don’t have an access to the scope that I’d like to alter.

To address the above listed issues, I sometimes use a simple debugging technique, that I call backdoor debugging. The idea is very simple: instead of (or in addition to) putting one or more “console.log” statements into some nested function scope(s), I am creating a closure in the deepest scope. The closure is doing just one thing: evaluating whatever code is passed into it. For example:

(function () {
  var totalNumberOfDrinks = 0;
  var totalNumberOfCodeLines = 0;

  var programmer = {
    writeCode: function () {
      totalNumberOfCodeLines += Math.floor(Math.random() * 100);
    },

    drinkCoffee: function () {
      totalNumberOfDrinks += Math.floor(Math.random() * 3);
    },

    isSleepy: function () {
      backdoor(function my(p) {return eval(p);});
      return Math.random() < .5;
    }
  };

  if (programmer.isSleepy()) {
    programmer.drinkCoffee();
  }

  var codeWritingInterval = setInterval(function () {
    programmer.writeCode();
  }, 100);

})();

The code is pretty simple: IIFE initializes a couple of variables (that I don’t have an access to from the global scope) and creates a “programmer” object. The programmer drinks coffee if sleepy and then starts writing some code - sounds familiar, doesn’t it?

I have also placed the “backdoor” named “my” inside “isSleepy” function, so now I can run arbitrary code with access to the “isSleepy” function and all scopes it is nested in. Let’s open console and have some fun. For example I can query how many lines of code have the programmer wrote so far, or even forever stop the programmer from writing code (sounds terrible though).

backdoor in action

The backdoor function is extremely simple. You can grab the source code from the backdoor.js repository. Any ideas about how to make it even more simple or extend it are welcome.