Javascript console API : 9 helpful tips
Tags: javascript, beginners
Published: 2020-01-27 13:51:29

If you daily work with javascript, I bet you use the `console.log` method a lot. But have you already tried to see what the `console` object looks like ?

Well, let's have a look :

![Alt console object](https://thepracticaldev.s3.amazonaws.com/i/tyyoffu2wqeh6hrurnm9.PNG)

As you can see, `console` object own far more methods than `log`. The purpose of this article is to demistify `console` API and show you what you can do with it. At the end of this article you should be able to display your logs correctly, evaluate performance of your code and debug your code more efficiently. This article should be useful if you use javascript both for browser or nodeJS !

## 🎛️ Use logging levels

Use different logging levels can be very useful to easily debug and observe how your application runs. Console API has several methods to log a message :

- [`log`](https://developer.mozilla.org/en-US/docs/Web/API/Console/log) : It will display general message in the console
- [`debug`](https://developer.mozilla.org/en-US/docs/Web/API/Console/debug) : It will display debug message in the console
- [`info`](https://developer.mozilla.org/en-US/docs/Web/API/Console/info) : It will display informative message in the console
- [`warn`](https://developer.mozilla.org/en-US/docs/Web/API/Console/warn) : It will display a warning message in the console
- [`error`](https://developer.mozilla.org/en-US/docs/Web/API/Console/error) : It will display a error message in the console 

Each of these methods can be used with two different ways.

- You can pass as argument one or more objects you want to display
- You can pass as first argument a string with [substitution strings](https://developer.mozilla.org/en-US/docs/Web/API/console#Using_string_substitutions) and each of these will pull the next argument in order to format the string.

Let's see an example :

```javascript
// with one or more objects as arguement
console.info("Toto", 1, object)

// Displays log :
// Toto 1 {test: 1}

// With the substitution strings
console.info("Hello, my name is %s. I am %d.", "Thomas", 30);

// Displays log :
// Hello, my name is Thomas. I am 30.
```

If you log a lot of messages, keep in mind that some browsers like Chrome or Firefox allow to filter logs with regex and logging level :

![Alt Chrome : console example with log filter](https://thepracticaldev.s3.amazonaws.com/i/e6v4vf1hzrkvbqj9lm3h.PNG)
<figcaption>Chrome : console example with log filter (exclude warning)</figcaption>

---

![Alt Firefox : console example with log filter](https://thepracticaldev.s3.amazonaws.com/i/kgvtn1858lspqxyn8kmy.PNG)
<figcaption>Firefox : console example with log filter (exclude warning)</figcaption>

Note that the logging level of messages produce with [`log`](https://developer.mozilla.org/en-US/docs/Web/API/Console/log) method can be different between browsers. For example Chrome will not make differences between [`log`](https://developer.mozilla.org/en-US/docs/Web/API/Console/log) and [`info`](https://developer.mozilla.org/en-US/docs/Web/API/Console/info) while Firefox will.

Finally, if you use nodeJS, you should know that `log`, `debug` and `info` are the same methods, they all print messages to `stdout`. `warn` and `error` are the same methods, they both print messages to `stderr`.

## 🗃️ Group logs

Sometime it can be useful to group your log messages in order to make them more readable. Console API has several methods to group log messages :

- [`group`](https://developer.mozilla.org/en-US/docs/Web/API/Console/group) : Creates a new inline group, indenting all following output by another level. To move back out a level, call [`groupEnd()`](https://developer.mozilla.org/en-US/docs/Web/API/Console/groupEnd).
- [`groupCollapsed`](https://developer.mozilla.org/en-US/docs/Web/API/Console/groupCollapsed) : Creates a new inline group, indenting all following output by another level. However, unlike [`group()`](https://developer.mozilla.org/en-US/docs/Web/API/Console/group) this starts with the inline group collapsed requiring the use of a disclosure button to expand it. To move back out a level, call [`groupEnd()`](https://developer.mozilla.org/en-US/docs/Web/API/Console/groupEnd).
- [`groupEnd`](https://developer.mozilla.org/en-US/docs/Web/API/Console/groupEnd) : Exits the current inline group.

Here is a trivial example :

```javascript
function sharedFunc(n) {
    console.group('sharedFunc', {n})
    for(let i = 1; i <= n; i++) {
	console.info('I have been called %d !', i)
    }
    console.groupEnd()
} 

function foo(n) {
    console.group('foo', {n})
    sharedFunc(n)
    console.groupEnd()
}

function bar(n) {
    console.groupCollapsed('bar', {n})
    sharedFunc(n)
    console.groupEnd()
}

foo(1)
bar(2)
bar(3)
foo(1)
```

The result of this will group your log messages by indenting them and making them more readable :

![Alt Chrome : Group log messages](https://thepracticaldev.s3.amazonaws.com/i/03gamba0un8ctltzqfme.PNG)
<figcaption>Chrome : Group log messages</figcaption>

You can see there is a little arrow next to each group that allow to fold or unfold the content of a group.

- When you use [`group`](https://developer.mozilla.org/en-US/docs/Web/API/Console/group) method, the group is automatically unfold
- When you use [`groupCollapsed`](https://developer.mozilla.org/en-US/docs/Web/API/Console/groupCollapsed) method, the group is automatically fold

Note that the interface may differ between browsers.

Finally, if you use nodeJS you will not have the ability to fold or unfold groups and only the indentation will be displayed. Consequently, [`group`](https://nodejs.org/api/console.html#console_console_group_label) and [`groupCollapsed`](https://nodejs.org/api/console.html#console_console_groupcollapsed) are the same method.

## ✅ Assert what is expected

Have you already written a piece of code which the goal is to debug by displaying a log message if something is wrong? Console API has a method to check an assert and display a log message if it is false:

- [`assert`](https://developer.mozilla.org/en-US/docs/Web/API/Console/log) : Log a message and stack trace to console if the first argument is `false`.

This method can be used with two different ways :

- You can pass as argument one or more objects you want to display
- You can pass as first argument a string with [substitution strings](https://developer.mozilla.org/en-US/docs/Web/API/console#Using_string_substitutions) and each of these will pull the next argument in order to format the string.

```javascript
const life = 42
const object = {test: 1}

// with one or more objects as arguement
console.assert(life === 43, 'toto', 1, object)

// Displays error log :
// Assertion failed: Toto 1 {test: 1}

// With the substitution strings
console.assert(life === 43, 'life should be %d', 42)

// Displays error log :
// Assertion failed: life should be 42
```

Here is the result you will have in Chrome :

![Alt Chrome : console.assert result](https://thepracticaldev.s3.amazonaws.com/i/ymcxiv2o3mu2unh90u6b.PNG)
<figcaption>Chrome : console.assert result</figcaption>

With this syntax you can write your debug code with a faster and easier way than a [`console.error`](https://developer.mozilla.org/en-US/docs/Web/API/Console/error) wrapped in a condition block.

Finally, if you use nodeJS, you should know that even if [`assert`](https://nodejs.org/api/console.html#console_console_assert_value_message) method works well, it sends log messages to `stdout`. It is recommended to use [assertion API](https://nodejs.org/api/assert.html) that provides more methods and sends log messages to `stderr` by throwing [AssertionError](https://nodejs.org/api/assert.html#assert_class_assert_assertionerror) when assertion is false.

## 🧮 Count code execution

While you are debbuging, you may want to know how many time a piece of code or a function is executed. Console API has several methods to log how many time your code has been executed :

- [`count`](https://developer.mozilla.org/en-US/docs/Web/API/Console/count) : Log the number of times this line has been called with the given label.
- [`countReset`](https://developer.mozilla.org/en-US/docs/Web/API/Console/countReset) : Resets the value of the counter with the given label.

The [`count`](https://developer.mozilla.org/en-US/docs/Web/API/Console/count) method associates a label with a count value in the same way as a map. Each time you will call the method you will increment the associate value by one and display its value in log. Note that if no label is given, the string 'default' is set as label. Let's see an example :

```javascript
function resetDay() {
   console.countReset('wake')
   console.countReset('exercise')
   console.countReset('eat')
   console.countReset('work')
   console.countReset('play')
   console.countReset('sleep')
}

for(let i = 0; i < 2; i++) {
   console.group(`day ${i}`) 
   console.count('wake')
   console.count('exercise')
   console.count('eat')
   console.count('work')
   console.count('eat')
   console.count('work')
   console.count('play')
   console.count('eat')
   console.count('sleep')
   resetDay()
   console.groupEnd() 
}
``` 

Here is the result you will have in Chrome :

![Alt Chrome : console.count result](https://thepracticaldev.s3.amazonaws.com/i/wsgcmz4sajexqs622jka.PNG)
<figcaption>Chrome : console.count result</figcaption>

## ⏱️ Time code execution

When your app seems to be slow you may want to start to time your code in order to know where you need optimizations. Console API has several methods to time your code execution :

- [`time`](https://developer.mozilla.org/en-US/docs/Web/API/Console/time) : Starts a timer with a name specified as an input parameter.
- [`timeLog`](https://developer.mozilla.org/en-US/docs/Web/API/Console/timeLog) : Logs the value of the specified timer to the console.
- [`timeEnd`](https://developer.mozilla.org/en-US/docs/Web/API/Console/timeEnd) : Stops the specified timer and logs the elapsed [`time`](https://developer.mozilla.org/en-US/docs/Web/API/Console/time)in seconds since it started.

Note that if no name is given, the string 'default' is set as name. Let's see an example :

```javascript
console.time('test')
setTimeout(() => {
   console.timeLog('test')
   setTimeout(() => {
       console.timeEnd('test')  
   }, 3000)
}, 3000)
```

Here is the result in Chrome : 

![Alt Chrome : Time the execution](https://thepracticaldev.s3.amazonaws.com/i/spulw3bw68vegkox7f2c.PNG)
<figcaption>Chrome : Time the execution</figcaption>

## 📍 Add markers

If you use browser performance tool, you should know that it is possible to add markers in the execution workflow. This displays events in the tool interface making your debugging easier. Console API has a method to do that :

- [`timeStamp`](https://developer.mozilla.org/en-US/docs/Web/API/Console/timeStamp) : Adds a marker to the browser's performance tools.

```javascript
console.timeStamp('test')
```

Here is the result in Firefox : 

![Alt Firefox Performance tool: console.timeStamp result](https://thepracticaldev.s3.amazonaws.com/i/3yjsylkzyyl49d9kcptb.png)
<figcaption>Firefox Performance tool: console.timeStamp result with string 'test'</figcaption>

## ✨ Display data in a table

When you want to display a complex object or array in the console, you should known that it is possible to display it as a table easying its read. Console API has a method to do that :

- [`table`](https://developer.mozilla.org/en-US/docs/Web/API/Console/table) : Displays tabular data as a table

Here is an example :

```javascript
const robert = {name: "Robert", age: "30", favoriteColor: "blue"}
const jack = {name: "Jack", age: "35", favoriteColor: "pink"}
const marie = {name: "Marie", age: "20", favoriteColor: "green"}
const tom = {name: "Tom", age: "24", favoriteColor: "yellow"}
const people = [robert, jack, marie, tom]

console.table(jack)
console.table(people)
```

Here is the result in Chrome : 

![Alt Chrome : console.table result](https://thepracticaldev.s3.amazonaws.com/i/s39dton3i0ydhmdwuyeb.PNG)
<figcaption>Chrome : console.table result</figcaption>

## 🔎 Display stack trace

While debugging you may want to know the call path of a point of your code execution while running. Console API has a method to display the stack trace :

- [`trace`](https://developer.mozilla.org/en-US/docs/Web/API/Console/trace) : Outputs a stack trace.

Here is how to use it :

```javascript
function foo() {
  function bar() {
    console.trace();
  }
  bar();
}

foo();
```

Here is the result in Chrome : 

![Alt Chrome : console.trace result](https://thepracticaldev.s3.amazonaws.com/i/nr92twqzuyz0b9kw90i8.PNG)
<figcaption>Chrome : console.trace result</figcaption>

## 🧼 Clean the console

When your console become a mess and you want to erase all of it, the console API provide you with a method to do that :

- [`clear`](https://developer.mozilla.org/en-US/docs/Web/API/Console/clear) : Clear the console.

Here is how to use it : 

```javascript
// This will clear the console
console.clear()
```

Here is the result in Chrome : 

![Alt Chrome : console.clear result](https://thepracticaldev.s3.amazonaws.com/i/1qqz2zyma5r4cx8pt9m7.PNG)
<figcaption>Chrome : console.clear result</figcaption>

## 🎉 Congratulations ! 

Congratulations ! You know all you need to know about console API ! Hope it will help you in your future debugging sessions.

If you liked this post, do not hesitate to :

- Follow me on twitter: [@tbetous](https://twitter.com/tbetous)
- Share this post !

Thank you for showing interest and reading this 🎉