Dec 11, 2020, Web

Debugging JavaScript – Tips and Tricks

Ireneusz Gabryś Front-end developer
image

But first – what the bug actually is?

The term “bug” describing defects was common among engineers since the 1870s and used in the context of error by Thomas Edison already back in 1878. In terms of computer error it was probably used for the first time in 1947 when an actual bug (moth) was found in Harvard Mark II computer.

A page from the Harvard Mark II electromechanical computer’s log, featuring a dead moth that was removed from the device.

We know that there are 2 types of developers. Those who debug with debugger using breakpoints and those who use console.log. This post should satisfy both sides.

debug(function)

It works only in Google Chrome console and on function and methods that you can access from global scope. All it does is invoking debugger and pausing code execution inside a given function once it’s called. Try this example (type in console):

The intended use is when you don’t debug your local code, finding the wanted function or method seems impossible in an obfuscated source, and you can access the function or method from the console.

DOM Breakpoints

You can add breakpoints that are not bound to line number but element modification. To do it right, click on the element in Dev Tools Elements inspector window. In the context menu choose “Break on” and then one of options.

All breakpoints added that way can be toggled in the debugger window in the “DOM Breakpoints” panel.

XHR Breakpoints

If you are trying to find a code responsible for sending specific requests, then use “XHR Breakpoints”, accessible from the debugger tab. You can specify any part of the URL and code execution will be paused once AJAX send() or regular fetch() methods will be called with that URL. If you don’t specify any URL in XHR breakpoint then execution will pause on every request.

dir(object)

It’s a less known method of logging objects in the console and makes no difference with regular console.log() if you pass a regular object as an attribute. The real difference is present when you pass an HTMLElement object. Try this in console:

console.dir() can be used both in code and in console but dir() works only in Google Chrome console.

Monitoring events

You can monitor specified event of specified DOM Element, like: “click”, “keyup” and “resize”. You can also keep track of all events but that might be overwhelming. This way of monitoring events is available only in Google Chrome console.

$() in console is an alias for document.querySelector().

Profile

You can profile code from Google Chrome console. It’s ideal when you like to start recording a few snapshots at the same time with different names.

Open profiles panel to see the results.

Share