Tutorial

A Look at the JavaScript Console API

Updated on April 16, 2020
author

Alligator.io

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

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Alligator.io

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.