JavaScript console is more than console.log()

One of JavaScript’s most straightforward approach to troubleshoot anything is to log stuff utilizing console.log. But the console provides many other methods that can help you debug better.

Let’s start with it. Logging a string or a lot of JavaScript objects is the very basic use case.

Just like this,

console.log('Where am I?');

Assume we have scenario when we have a lots of objects and need to log them into console.

const foo = { id: 1, height: '200px', width: '100px' };
const bar = { id: 2, height: '250px', width: '200px' };

Only console.log(variable) one after the other is the most intuitive way to log this. When we see how it appears on the console, the problem becomes more apparent.

Variable names are not visible

As you can see, variable names are not visible. Sometimes, it gets hard or annoying when you have lots of outputs and have to expand one by one each of them to understand which object or variable is it.

One solution to avoid this is to use console.log as this:

console.log({ foo, bar });

This also reduces the number of console.log lines in our code.

console.warn() & console.error()

Depending on the situation, you can add logs using console.warn() or console.error() to make sure that your console is more readable. In some browsers, console.info() also displays an ‘i’ icon.

console.error() and console.warn()

console.group()

This can be used when grouping or nesting together relevant details to enable you to read the logs easily.

This can also be used if you have a few log statements within a function and you want the scope of each statement to be clearly visible.

For example, if you log the details of a shopping cart:

console.table()

We can take this one step further by putting all these in a table together to make it more readable. Use console.table() every time you have objects with common properties or an array of objects. Console.table({foo, bar }) can be used here and the console displays:

console.table()

console.trace()

This will show you the call path taken to reach the point at which you call console.trace()

console.time()

Starts a timer you can use to track how long an operation takes. You give each timer a unique name, and may have up to 10,000 timers running on a given page. When you call console.timeEnd() with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started.

console.time()

console.clear()

Clears the console. The Console’s contents will be replaced with an informational message like “Console was cleared”.

console.dir()

console.dir is the way to see all the properties of a specified JavaScript object in console by which the we can easily get the properties of the object.

Like to learn?

Follow me on twitter where I post all about the latest and greatest JavaScript, AI, DevOps, VR/AR, Technology, and Science! Connect with me on LinkedIn too!