Yay! Programmer art!
Yay! Programmer art!

Enumerating Local Variables in JavaScript

One day I was trying to do some debugging in browsers other than FireFox (FireBug rocks and is highly recommended). I decided it would be useful if I could enumerate local variables such that I could quickly find and display their values in an alert box. Unfortunately, there didn’t appear to be any way to do that in some browsers. So the solution I came up with was to parse the function text itself (which can be found with func.toString()) to find all the local variables.

Of course there are a couple problems with this method. First of all my parsing is very limited. I didn’t want to write a JavaScript interpreter. Second, to get the values of the variables an evaluation function has to be passed in (trick found from TrimBreakpoint). And I’m sure there are other problems I can’t think of at the moment. :)

Anyway, on to the example. One of the interesting aspects of this method is the ability to see closure values from outside the function (click the third button in the example). Use View Source to get the full source from the example.

Example of Enumerate Local Variables

Example Calls to Show Locals


      function doItInside(s) {
        var x = 5, y = 9;
        var re = /^test$/;
 
        for (var i = 0; i < 5; i++) {
          var arr = [ 2, 4, 6, 8 ];
 
          if (arr[i] == i) {
            break;
          }
        }
 
        var ob = { x: 7, y: 5 };
 
        showLocals(function($$$$){return(eval($$$$))}, arguments);
      }
 
      var outsideCheckerFunc;
      function doItOutside(str_param, num_param) {
        var timer = 100;
        outsideCheckerFunc = function($$$$){return(eval($$$$))};
 
        var f = function(){alert("hi")};
        var a = 55, b = 66, c = 77;
        var regE = new RegExp("^s*tart?");
      }
 
      function doItOutsideCaller(withEvalFunc) {
        if (withEvalFunc) {
          doItOutside('test param string', 9);
          showLocals(outsideCheckerFunc, doItOutside);
        } else {
          showLocals(null, doItOutside);
        }
      }

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*

For spam detection purposes, please copy the number 5787 + 1 to the field below: