A Look at the JavaScript Console API

The JavaScript console is an invaluable tool to help develop and debug our apps. With the console object and its logging methods, long are the days of of calling alert() to debug and get a variable’s value. On top of that, thanks to a work in progress standard, modern browsers are finally supporting the same set of methods. In this post we’ll explore some of the main methods made available by the console API.

Logging

console.log is the usual method we use to log values out to the console:

const name = 'Alligator';
console.log('Hello', name); // Hello Alligator

But we also have access to more logging methods like warn, info and error:

console.info('Just FYI');
console.warn('Lookout!');
console.error('Boom 💣');

As you can see from the resulting console output, using the warn or error methods also gives us a stack trace:

Logging outputs

You can also trigger a stack trace with console.trace:

function hello(name = 'Alligator') {
  console.trace('name:', name);
  return `Hello ${name}!`;
}

hello();

…Oh, and there’s also console.debug, but it’s currently just an alias for console.log.

console.dir & console.dirxml

console.dir prints out objects in a nice formatted way:

const fancyThings = {
  car: '🏎️ Ferrari',
  watch: '⌚ Cartier',
  clothing: {
    shoes: '👠 Christian Louboutin',
    dress: '👗 Versace'
  },
  boat: '🛥️ Sunseeker'
}

console.dir(fancyThings);

Output of console.dir


As for console.dirxml, it prints out a DOM element’s markup. For example:

<!DOCTYPE html>
<html lang="en">

<head>
  <!-- ... -->
</head>

<body>
  <h1>hello</h1>

  <script>
    console.dirxml(document.body);
  </script>
</body>

</html>

This will output the following:

Output of console.dirxml

If you feel so inclined, you can even display data in the console more neatly in a table format using console.table.

Asserting

The console.assert method is an easy way to run simple assertion tests. The assertion fails if the 1st argument evaluates to false, and the subsequent arguments get printed to the console if the assertion fails:

// this will pass, nothing will be logged
console.assert(2 == '2', '2 not == to "2"');

// this fails, '3 not === to "3"' will be logged
console.assert(3 === '3', '3 not === to "3"');

Clearing

You can clear the console with console.clear:

console.clear();

Counting

The console.count method is used to count the number of times it has been invoked with the same provided label. For example, here we have two counters, one for even values and one for odd values:

[1, 2, 3, 4, 5].forEach(nb => {
  if (nb % 2 === 0) {
    console.count('even');
  } else {
    console.count('odd');
  }
});

// odd: 1
// even: 1
// odd: 2
// even: 2
// odd: 3

Timing

As we’ve showed in this short post, you can start a timer with console.time and then end it with console.endTime. Optionally the time can have a label:

console.time('fetching data');
fetch('https://jsonplaceholder.typicode.com/users')
  .then(d => d.json())
  .then(console.log);
console.timeEnd('fetching data');

// fetching data: 0.2939453125ms
// (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

Note that if you use a label with console.time you must pass-in that same label when calling console.timeEnd.

Grouping

Use console.group and console.groupEnd to group console messages together with an optional label. Notice also how a group can be nested into another one:

console.group('🖍️ colors');
console.log('red');
console.log('orange');
console.group('HEX');
console.log('#FF4C89');
console.log('#7186FE');
console.groupEnd();
console.log('blue');
console.groupEnd();

Here’s the resulting console output:

Output of console.group

Bonus: Giving it Some Style

Console logging can be styled using a special %c delimiter:

console.log(
'Hello %cAlligator%c!',
'color: #008f68; font-weight: bold; font-size: 2rem; text-shadow: 0 0 5px rgba(0,0,0,0.2);',
'color: hotpink; font-weight: bold; font-size: 2rem; text-shadow: 0 0 5px rgba(0,0,0,0.2);'
);

Everything that comes after the first %c will be styled by the string provided by the second argument, then everything after the next %c is styled by the following string argument, and so on. Here’s how the above example looks like at the console:

Result of styling console output

  Tweet It

🕵 Search Results

🔎 Searching...