Chrome Debugger and Firebug Surprises

- - | Comments

The Chrome JavaScript debugger and Firebug are optimized beasts, but sometimes I get bit by one feature that I’m not expecting. It happens rarely enough that it always takes me a few seconds of WTF thinking before I remember. While debugging, if you try to use a variable from a closure scope in the console, that wasn’t actually used in the source, you’ll be surprised by ReferenceErrors like in:

This is because JavaScript debuggers optimize the hell out of your code and will remove variables from the Lexical Environment of a function if they are unused. See my previous post about hoisting for more information about the Lexical Environment. If you use these variables anywhere in your source, suddently they will be accessible again inside of the scope of the new function.

You don’t even have to actually cause any side effects in order to make sure they’re not removed. Just including the identifier in the source of the function will keep their values around.

Hopefully this will prevent some rare moments of JavaScript inadequacy that might strike when debugging. Don’t worry, it’s not you, it’s the debugger.