Different Use Cases of console.log - You should use when debugging JavaScript
Tags: javascript, webdev, productivity
Published: 2020-07-24 08:28:35

Working in JavaScript? Then you're very familiar with `console.log()`. Like all javascript programmers, I frequently throw a `console.log` into my code. And I really found it the simplest, faster, and a plain way to log something.

```javascript
(() => {
    // do stuff
    let msg = 'Success!';
    console.log(msg);
})();
```
![plain JS console.log](https://dev-to-uploads.s3.amazonaws.com/i/cg6g3vzwz1j8z9uxp560.jpg)

Let's see a few more ways in regards to console logging, that I found a bit more informative, and interesting in my day-to-day development workflow!🙌 😊

### 1. Common usage: debug(), info(), log(), error(), and warn()
Technically `console.debug()` `console.info()` and `console.log()` are identical - the only difference is that debug messages are hidden by default and log messages are visible in the recent versions of Chrome (to see debug messages, you have to set the log level to `Verbose` in the Devtools).

```javascript
(() => {
    // do stuff
    console.debug('console.debug()');
    console.info('console.info()');
    console.log('console.log()');
    console.error('console.error()');
    console.warn('console.warn()');
})();
```
![common usage of the console.log](https://dev-to-uploads.s3.amazonaws.com/i/tts3qcffc2oq9gb6g3i2.jpg)

`console.debug` Pure black color text
`console.info` Black color text with no icon
`console.log` Black color text with no icon
`console.error` Red Color text with icon
`console.warn` Yellow color text with icon

### 2. Stop variable name confusion
When logging many variables, sometimes it’s difficult to understand what log corresponds to which variable.

For example, let’s try the code snippet in below:

```javascript
const sum = (numOne, numTwo) => {
    // do stuff
    console.log(numOne);
    return numOne + numTwo;
};
console.log(sum(2,3));
console.log(sum(5,8));
```
When the above code is executed, you’ll see just a series of numbers.

![console.log-img3](https://dev-to-uploads.s3.amazonaws.com/i/wans1rtjx6tw76vq5gla.jpg)

To make an association between the logged value and variable, wrap the variable into a pair of curly braces `{numOne}`.

```javascript
console.log({numOne});
```
Now in your console, you can see the associate variable name with the log.

![console.log-img4](https://dev-to-uploads.s3.amazonaws.com/i/16uue1b9eg4ko5np7l02.jpg)

### 3. String substitution
If you want a message containing multiple variables, string substitution is useful in this circumstance. It allows us to insert different variables that describe a message and make it clear as exactly what it needs to be.

```javascript
(() => {
    // do stuff
    const user = 'John';
    const age = 25;
    console.log('%s is %i years old', user, age);
})();
```
![console.log-img5](https://dev-to-uploads.s3.amazonaws.com/i/y4lhtorhab0uazy5kj5k.jpg)

Here is a list of specifiers that can be substituted into the output string:

| Data type          | Specifier   |
| ------------------ |:-----------:|
| Objects and arrays | `%o` or `%O`|
| Integers           | `%d` or `%i`|
| Strings            | `%s`        |
| Floats             | `%f`        |

### 4. console.group() and console.groupEnd()
We can make a group of the related log by surrounding them with the `console.group()` and `console.groupEnd()` statements.

```javascript
(() => {
    // do stuff
    console.group("Details of URL");
    console.log("Protocol: HTTPS");
    console.log("Domain: example.com");
    console.log("Path: details")
    console.groupEnd();
})();
```
![console.log-img6](https://dev-to-uploads.s3.amazonaws.com/i/yo1gsfvr5sz7rw4mt6x9.jpg)

**Note:** The group created by `console.group()` is initially opened. If you'd prefer that to be collapsed by default, you can use the `console.groupCollapsed()` statement instead of `console.group()`:

```javascript
console.groupCollapsed("Details of URL");
```
![console.log-img7](https://dev-to-uploads.s3.amazonaws.com/i/8a7fmo7oj1w1w6wr0qja.jpg)

### 5. console.time() and console.timeEnd()
`console.time()` and `console.timeEnd()` are mostly used when you need to check the performance.

```javascript
console.time("Loop");

for (var i = 0; i < 10000; i++) {
  // do stuff
}

console.timeEnd("Loop");
```
![console.log-img8](https://dev-to-uploads.s3.amazonaws.com/i/3xlfvll0r6mmwinebuo7.jpg)

### 6. Log with style
By default, `console.error()` and `console.warn()` came up with certain different colors to draw attention. Let’s try to replicate this feature in our usual `console.log()` statement.

```javascript
(()=>{
    // do stuff
    console.log(`%cThis is an important text`,`background: #FF0000; color: #FFFFFF; padding: 5px`);
})();
```
![console.log-img9](https://dev-to-uploads.s3.amazonaws.com/i/oh3wiz4e4ng1bskketgw.jpg)

Let's write a code snippet that lets us use "our own" log directly with different colors:

{% gist https://gist.github.com/fatematzuhora/73b33071b0c4cbebd19cf44a58317592 %}

Now let's use the above code to write our log:

```javascript
log.info('console info');
log.warn('console warn');
log.success('console success');
log.error('console error');
```
![console.log-img10](https://dev-to-uploads.s3.amazonaws.com/i/71l1h2rtudqyb2ixp7ym.jpg)

### 7. console.table()
`console.table()` is exactly what it sounds like. It allows us to log the data to the console as a table.

Let's say we have an array of programming languages:

```javascript
let languages = ["JavaScript", "TypeScript", "Python", "PHP"]
```
The `console.log()` call will give you the following representation of your data:

![console.log-img11](https://dev-to-uploads.s3.amazonaws.com/i/a0kjazn83rn6l3ssti44.jpg)

However, with `console.table()` we get:

![console.log-img12](https://dev-to-uploads.s3.amazonaws.com/i/d0nitwmdteh9qr9rzsk8.jpg)

Let's look at an object:

```javascript
let extensions = {
    javascript: ".js",
    typescript: ".ts",
    python: ".py",
    php: ".php"
}
```
With `console.log` we get:

![console.log-img13](https://dev-to-uploads.s3.amazonaws.com/i/kgnpwif1nu6nbnriw8m6.jpg)

While `console.table` gives us:

![console.log-img14](https://dev-to-uploads.s3.amazonaws.com/i/rr57k8dt3o7potpfkvrp.jpg)

Let's log an array of objects:

```javascript
let languages = [
  {name: "JavaScript", extension: ".js"},
  {name: "TypeScript", extension: ".ts"},
  {name: "Python", extension: ".py"},
  {name: "PHP", extension: ".php"}
];
```
![console.log-img15](https://dev-to-uploads.s3.amazonaws.com/i/kqhxovk804ry52gt6394.jpg)

You can also restrict the columns that are shown in the table. You have to just pass their keys as an array into the second parameter while throwing the `console.table()`:

```javascript
console.table(languages, ["extension"]);
```
![console.log-img16](https://dev-to-uploads.s3.amazonaws.com/i/nbpde5cgueu2wsly8omc.jpg)

### That's It!
Hopefully, you found these debugging tricks useful and these will make your JavaScript coding experience more productive.

What logging tips do you use? Write a comment below!