šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Beyond console.log() – 3 Console methods you can use for better Javascript debugging

We can enhance our Javascript debugging experience using a set of less known features of the Console utility.

1. Using CSS with console.log

You can style your console log messages. You need to add the %c flag alongside a second parameter containing the actual CSS styles. For example:

console.log("%cA green message", "background-color: green; padding: 5px; color: white");

will output the following:

2. Using console.table() and console.dir() to print objects.

The plain console.log() is meant to print single lines. However, if you want to print objects console.table() and console.dir() are a better fit.

For example, if we have the following objects:

const firstChar = {name: "Han Solo", age: 35};
const secondChar = {name: "Chewbacca", age: 190};

The console.table(firstChar) will give the following nice formatted output:

And we can use table also with an array of objects.

console.table([firstChar, secondChar]);

Will output:

3. Adding new flavors: console.warn() and console.error()

And maybe the easiest commands to add to your toolbelt are the different levels of errors in showing up a message:

console.log("a simple log"); // no alter
console.warn("pay attention!"); // yellow alert 
console.error("a serious error !!!"); // red alert

This will output:

Disclaimer: when it comes to finding what is wrong with your Javascript code, please keep in mind that in the vast majority of cases it's faster to use tools like the javascript debugger from Google Chrome DevTools or Firefox instead of the plain old console.log.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *