Easy debugging with window.q = this

December 25, 2016

TL;DR: Sprinkle a quick window.q = this into your JS file for a quick and easy way to debug from your browser's dev tools.

Modern JS techniques generally prohibit application code from adding or modifying global variables, so the scope of various classes that contain an applications state and functionality are not directly accessible from a browser's debug console. This is an annoyance for debugging.

For instance, a simple top-level React component may look like:


class MyApp extends React.Component {
  constructor() {
    super();
    this.state = {
      value: null,
    };
  }
  ...
}

There's no way to access MyApp.state from the browser's dev tools. The obvious way to do this is to put in a breakpoint or a watch, but what if you want the scope to be always accessible directly from the console, so you can always inspect state or execute any arbitrary method? The simpliest way that I have learned to this is just to add something like window.q = this inside the constructor() (feel free to replace the name with whatever you want).


class MyApp extends React.Component {
  constructor() {
    window.q = this;
    super();
    this.state = {
      value: null,
    };
  }
  ...
}

It has no real effect on the execution of the code, doesn't cause execution to stop or anything and is very trivial to set up (particularly if finding the right line to break on is difficult). It gives you easy access to an arbitrary scope, anywhere in your project.

Sometimes the solution which seems hacky is perfectly viable, especially if you're just debugging something. Just be sure to remove the line before committing your code!