Useful Browser Console Tips

Published on

While debugging JavaScript can be difficult, there are a lot of tools and shortcuts that browsers provide to help us along. A lot of these are easy to forget about, so I’ve put together a list of the ones that I find to be the most helpful.

Many of us are familiar, I’m sure, with the console found in the developer tools, as well as the console JavaScript API. These can be very powerful and useful for us whenever we’re debugging, but if you’re anything like I was before I started reading up on it, we do the majority of our debugging by using console.log and figuring the rest out from there.

As it turns out, we’ve just been doing it the hard way all along. So, I’m going to let you in on my favorite functionality of the console and the console API. I won’t cover all the features or methods because there are a lot of them and browser creators generally do a good job of documenting this stuff. There is a list of links to console documentation for different browsers at the end of this article.

Console API Methods

These are the methods that you can call from within your JavaScript.

assert(expr, obj)

You may want to output something to the console based on a conditional expression. Instead of writing an if statement, you can use console.assert. If the expression returns false, object will be logged to the console.

// only log if the number isn't evenly divisible by two
for (var i = 0, l = 10; i <= l; i++) {
    console.assert(i % 2 === 0, i);
}

/**
 * Output:
 * Assertion failed: 1
 * Assertion failed: 3
 * Assertion failed: 5
 * Assertion failed: 7
 * Assertion failed: 9
 */

clear()

The console can get pretty cluttered after a bit of debugging, and sometimes it helps to clean it up. Using console.clear will completely clean out the console output and give you a blank slate. Note that this may not work if you have your developer tools set to preserve the console log. Browsers will also generally provide a clear() console command-line function that does the same thing.

dir(obj)

Have you ever tried to output an HTML Element to get the JavaScript object representation, only to get a DOM visualization instead? console.dir is useful for those times when you only want to see a JavaScript object representation.

log(obj[, obj, ...])

When you want to write some output to the console, console.log will get it done. A nicety of this method is that you can log multiple things at once, because it accepts multiple arguments. Another nice feature is that you can pass a format string as the first argument, and the rest of the arguments will be formatted based on that string.

var greeting = 'Hello World!';
var arr = [1, 2, 3];
var obj = {
    a: 0,
    b: 1,
    c: 2
};

console.log(greeting);

/**
 * Output:
 * "Hello World!"
 */

console.log(greeting, arr, obj);

/**
 * Output:
 * Hello World! [1, 2, 3] Object {a: 0, b: 1, c: 2}
 */

console.log('"%s" is %d characters long.', greeting, greeting.length);

/**
 * Output:
 * "Hello World!" is 12 characters long.
 */

group(obj[, obj, ...])
groupEnd(label)

Another way to bring organization to a cluttered console is to group the output. You basically call console.group with a label (it can use the same formatting as console.log, above), and any console output that occurs before console.groupEnd is called will be grouped underneath that group label.

console.group('API call');
...
console.log('XHR sent');
...
console.log('XHR response');
...
console.log('done');
console.groupEnd();

/**
 * Output:
 * API call
 * |  XHR sent
 * |  XHR response
 * |  done
 */

profile([label])
profileEnd([label])

A great way to find out what piece of your JavaScript is taking the most time, or running poorly, is to start a CPU profile for it. You can do this by calling console.profile with an optional label. Once the profile is complete, you can call console.profileEnd, and the profile results will be added to the Profiles section of your developer tools.

console.profile();
$.ajax('http://localhost').done(function() {
    console.profileEnd();
});

/**
 * Output:
 * Profile 'Profile 1' started.
 * XHR finished loading: GET "http://localhost/".
 * Profile 'Profile 1' finished.
 */

time(label)
timeEnd(label)

Another great way to find out if a particular part of your JavaScript is running slowly is to simply time it. console.time will create a new timer with an associated label. The timer is stopped and the time is output to the console when console.timeEnd is called. The label used for console.time and console.timeEnd is not optional, and the label must be equal.

console.time('initialize array');
var arr = new Array(1000000);
for (var i = arr.length - 1; i >= 0; i--) {
    arr[i] = new Object();
};
console.timeEnd('initialize array');

/**
 * Output:
 * initialize array: 1160.917ms
 */

Console Command-Line Methods

The command-line methods can be used directly in the console without being called from JavaScript.

$_ (Chrome/Safari only?)

How many times have you been trying things out in the console and you’ve copied/pasted the output, or you’ve had to reevaluate an expression, just so you can use it in another expression? Enter $_, which will give you the output of the previously run expression. This works for all kinds of data types, too, like objects and full DOM elements.

document.querySelector('p');

/**
 * Output:
 * <p>Hello World!</p>
 */

$_.textContent;

/**
 * Output:
 * "Hello World!"
 */

$(selector)

This might look like a jQuery statement, but you can use this on a page without jQuery. In modern browsers, we have the ability to use document.querySelector, and $ is simply an alias for that method. This won’t interfere with jQuery, either, because $ will just map to jQuery (or anything else using the $ variable name) if it’s loaded.

$$(selector)

Just as $ is an alias for document.querySelector, $$ is an alias for document.querySelectorAll.

$0 - $4

Finally, it can get a little tedious when you need to inspect an element to take a closer look at it, and then you need to go to the console and select it again with JavaScript to interact with it. Thankfully, many browsers will remember the last few elements that you’ve selected in the inspector, and you can refer to them using $<n> in the console.

Wrapping Up

We’ve looked at the methods that I’ve found to be the most useful, but there are even more available that you can find in the documentation for your particular browser console. Going beyond the console, there is so much more to browser developer tools as a whole. Getting to know your tools can be incredibly beneficial, so take some time to sit down and read about them.

Resources

As promised, here are some links to the documentation for a few browser’s consoles.


Verify the signed markdown version of this article:

curl https://keybase.io/sethlopez/key.asc | gpg --import && \
curl https://sethlopez.me/article/useful-browser-console-tips/ | gpg