JavaScript Console Tips. Other console tools in JavaScript
Tags: javascript, console, consolelog, debugg
Published: 2023-03-01 09:37:56

**1.console.log()**
Let’s imagine we have a variable called name and we want to log it in the console.

Often we find ourselves writing this:
```
console.log('name', name)
```
Since ES2015, we can use object shorthand notation whenever we want to log out things like this. That means we can write the following:
```
console.log({name})
```
And this will output the same thing.

**2. A better way to log multiple items**
Imagine a scenario when you have a bunch of objects you need to log into the console.
```
const sunil = { name: "Sunil", member: true, id: 134323 };
const ilaria = { name: "Ilaria", member: false, id: 489348};
If we were to console.log() these out individually, like so:

console.log(sunil)
console.log(ilaria)
```

It would be slow, tedious, and would not display the variable names alongside the logged data

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vfrsopuub1g32fwv32wy.png)

Instead, we can use our good friend from the first example!

console.log({sunil, ilaria})
And this will give us a better formatted, quicker solution to console.logging multiple items, and will display the variable names alongside each!


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wo389oi12x91gsy228fa.png)

**3. Why use lines when you can use tables?**
We can take this a step further by putting all of these together in a table to make it more readable. Whenever you have objects with common properties or an array of objects use console.table() . Here we can use console.table({ foo, bar}) and the console shows:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2015pjtrz6xs3lhuedrp.png)
**4. Group grouped logs**
This can be useful for those moments when you are logging a lot of different things and want to group or nest relevant details together.

Maybe you are logging information in a few different functions and you want a way to clearly label which function the information is coming from.

For example, if you’re logging a user’s details:

```
console.group('User Details');
console.log('name: Sunil Sandhu');
console.log('position: Software Developer');
console.groupEnd();console.group('Account');
console.log('Member Type: Premium Member');
console.log('Member Since: 2018');
console.log('Expiry Date: 20/12/2022');
console.groupEnd();
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0nnpcmrazmamfrhcydoi.png)

You can even nest groups inside of others if you want:
```
console.group('User Details');
console.log('name: Sunil Sandhu');
console.log('position: Software Developer');console.group('Account');
console.log('Member Type: Premium Member');
console.log('Member Since: 2018');
console.log('Expiry Date: 20/12/2022');
console.groupEnd();
console.groupEnd();// notice that we have two groupEnd() calls at the end as we want to nest 'Account' inside of 'User Details'
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j3t7w6r2oue86uhhu81c.png)

**5. Better warnings**
Want to increase the visibility of certain bits of information being logged? console.warn() will display information with a yellow background:
```
console.warn('This function will be deprecated in the next release')
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z30up6uh71tc13z48r0g.png)

**6. Better error logging**
Maybe you want to take things one step further and use the same type of logging you get whenever you receive those scary red console logs. You can achieve that like so:
```
console.error('Your code is broken, go back and fix it!')
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8zh0n3euhayjpwg7b1fz.png)

**7. Custom console styling**
Take your CSS skills and start using them in the console!

You can use a %c directive to add styling to any log statement.
```
console.log('%c React ', 
            'color: white; background-color: #61dbfb', 
            'Have fun using React!');
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tk6xu7bqxnezz0egjl58.png)

**8. Time the speed of your functions**
Ever been curious to know how fast a particular function runs? You can write something like this:
```
let i = 0;
console.time("While loop");
while (i < 100000) {
  i++;
}
console.timeEnd("While loop");console.time("For loop");
for (i = 0; i < 100000; i++) {
  // For Loop
}
console.timeEnd("For loop");
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4xazkdpjpot487ztdfdf.png)

It’s worth bearing in mind that the speeds you see here are not static. In other words, it can give you an idea of which is faster between the two at that exact moment in time, but other factors influence this, such as the computer it is running on, other things being executed at the time etc. In fact, if we run this 5 more times, we will see different results for each:

 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/46s3dhov42d7thprmiov.png)

**9. Better stack traces**
console.trace() outputs a stack trace to the console and displays how the code ended up at a certain point. This can really come in handy when trying to debug complex code that might be making calls in lots of different places. While the following is not an example of “complex code”, it’ll at least explain how this works:
```
const sunil = {name: "Sunil", member: true, id: 134323};function getName(person) {
    console.trace()
    return person.name;
}function sayHi(person) {
    let _name = getName(person)
    return `Hi ${_name}`
}
The console.trace() would return this:
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lx4ftz5glsoo733v5ocq.png)

We can click on those blue links and it will take us to the moment where that console.trace() was made in our code.

**10. console.trace()**
console.trace() works the exact same as console.log(), but it also outputs the entire stack trace so you know exactly what's going on.
```
const outer = () => {
  const inner = () => console.trace('Hello');
  inner();
};
outer();
/*
  Hello
  inner @ VM207:3
  outer @ VM207:5
  (anonymous) @ VM228:1
*/
```
**11. Logging levels**
There are a few more logging levels apart from console.log(), such as console.debug(), console.info(), console.warn() and console.error().
```
console.debug('Debug message');
console.info('Useful information');
console.warn('This is a warning');
console.error('Something went wrong!');
```

**12. Formatting**
The console.log() method also allows you to add some styling to your messages. To do that you need to add a %c specifier to your message and pass CSS styling as an additional parameter to the log() method.
```
console.log('%c console.log is awesome', 'color: green; font-size: 16px');
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5bvvp16ooitkwfuw5cth.png)

We can click on those blue links and it will take us to the moment where that console.trace() was made in our code.

**10. console.trace()**
console.trace() works the exact same as console.log(), but it also outputs the entire stack trace so you know exactly what's going on.
```
const outer = () => {
  const inner = () => console.trace('Hello');
  inner();
};
outer();
/*
  Hello
  inner @ VM207:3
  outer @ VM207:5
  (anonymous) @ VM228:1
*/```

**11. Logging levels**
There are a few more logging levels apart from console.log(), such as console.debug(), console.info(), console.warn() and console.error().

```
console.debug('Debug message');
console.info('Useful information');
console.warn('This is a warning');
console.error('Something went wrong!');```

**12. Formatting**
The console.log() method also allows you to add some styling to your messages. To do that you need to add a %c specifier to your message and pass CSS styling as an additional parameter to the log() method.

console.log('%c console.log is awesome', 'color: green; font-size: 16px');

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xfeyfrkjgnx0ddjc2597.png)

**13. console.table**
Use console.table() to display object or array data as a table.
```
const user = {
  name: 'Jon Doe',
  age: 42
}
const fruits = ['banana', 'apple', 'kiwi']
console.table(user)
console.table(fruits)
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ilmjg5j2uga20om1xtd5.png)

**14. console.trace**
A handy method to log to console the stack trace. It will show you the function call path up until your console.trace() call. Quite useful during the debug process to instantly show which functions gets called.
```
function toggleClass(el, className) {
  el.classList.toggle(className);
  console.trace('toggleCLass')
}
function handleClick(e){
  toggleClass(e.currentTarget, 'active')
}
const heading = document.getElementById('main-heading')
heading.addEventListener('click', handleClick)
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zqeqxx9ev6cxn4xibs4u.png)

**15. console.count**
A method acts as a counter and is used to output the number of times the particular count() method has been called.

You can pass a string (label) as an argument and it will output like a regular console.log with a number next to it. If no argument is specified then the default label will be shown.

```
function handleClick(){
  console.count('click count')
}
const heading = document.getElementById('main-heading')
heading.addEventListener('click', handleClick)
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g5rvowq6ynq2hrbl4wf1.png)