JS debugging tricks

When working with large complex SPAs one may hit situations where one has to think beyond the usual debugging tricks.
 Here I list a few of them I had to use at work:

  • Profiling performance with Dev tools Profile option: With Fixefox dev tools, one can not only see the Total time and Own time spent by each function, but also the number of calls made to that function. That sometimes helps in detecting unusual number of calls to functions.
  • Using console.profile() and console.profileEnd() helps to figure out how much time is spent on a specific code fragment within a function. Useful for tracking down performance bottlenecks.
  • Debugging event.stopPropagation() and event.preventDefault() is a pain sometimes, since you have no idea from where in the code (and from which element’s listeners) the call is being made (since someone else wrote the code or yourself wrote it and forgot).
     The trick to figure that out is to override Event.prototype temporarily in the dev console as follows:
Event.prototype.stopPropagation = (function () {
var old = Event.prototype.stopPropagation;
return function () {
debugger; //or console.trace() or console.log() or whatever
old.apply(this, arguments);
  • If you are using break points or debugger statements in a function that is called several times and you are unsure as to when and who will call the function next (to replicate some bug you are seeing), then it is useful to use console.trace() to log the entire call stack, rather than clicking debugger’s ‘resume’ button several times.

Article re-posted from my website codepasta.com.