In an ideal world, every piece of code would have multiple tests, any regressions immediately pin-pointed to a specific commit, and all commits would be of a reasonable size with a sensible message.
I don’t live there (which may partially be my own fault), and you probably don’t either. Here are a few debugging tricks that have served me well, I hope they’ll be of some use for you as well (just don’t accidentally commit any of this).
We’ve all looked upon jumbled messes of variables, operations and method calls and wondered — #@&?
Let’s say you find a bug where the value of
foo has turned out to sometimes be incorrect:
I’ll assume everyone knows how to use breakpoints and
debuggers. Those are great tools, but sometimes problematic code may be in a place where it's difficult to place a breakpoint, or perhaps you don't want to hassle with pausing script execution.
One quick and dirty way to log out what the values are without majorly restructuring your code is this:
This works because
undefined || val returns
val. Horrid, ugly, but boy is it quick! You’re not checking this code in anyway so what does it matter?
A problem though is that as you’re debugging and tweaking the code, you may forget to sync the original values and what’s being logged out.
Here comes a utility function!
Now you can do this:
Perhaps you’d like to tag the logs with something so that they can be differentiated：
In my article on Using AngularJS (Angular 1) components & directives inside React, I wrote about how we ran into an issue where the brower’s address bar was sporadically being reset. I knew that Angular was most likely calling
history.pushState, but still needed to find out where and why it was doing that before I could figure out how to fix it.
This is what I did:
Whenever something calls
history.pushState, it'll get my modified version which will print out a stack trace, letting me know who the caller was.
You could abstract this out to a utility function that can be applied to other places. (updated based on suggestions from Greg Lockwood)
Let’s try that on
There have been a surprising number of times where I’ve had to deal with multiple versions of Lodash and Underscore overwriting each other.
To figure out why that was happening, a similar trick could be used to see when a property is assigned a new value by taking advantage of
Here comes another utility function
Let’s try overwriting
Please leave a comment or tweet at me @CheapSteak to let me know about any other debugging tricks that you’ve found useful
Really appreciate Jeffrey Burt and Anne Thomas for proofreading and feedback, and Greg Lockwood for the suggestion of returning the value of
traceFn and including these as a “snippet” in Chrome Dev Tools.
Thanks for reading😄