DEV Community

Himanshu Gupta
Himanshu Gupta

Posted on

JavaScript Console Tips. Other console tools in JavaScript

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)
Enter fullscreen mode Exit fullscreen mode

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})
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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

Image description

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

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
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();
Enter fullscreen mode Exit fullscreen mode

Image description

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'
Enter fullscreen mode Exit fullscreen mode

Image description

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')
Enter fullscreen mode Exit fullscreen mode

Image description

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!')
Enter fullscreen mode Exit fullscreen mode

Image description

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!');
Enter fullscreen mode Exit fullscreen mode

Image description

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");
Enter fullscreen mode Exit fullscreen mode

Image description

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

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:
Enter fullscreen mode Exit fullscreen mode

Image description

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
*/
Enter fullscreen mode Exit fullscreen mode

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!');
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

Image description

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().



Enter fullscreen mode Exit fullscreen mode

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

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)
Enter fullscreen mode Exit fullscreen mode

Image description

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)
Enter fullscreen mode Exit fullscreen mode

Image description

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)
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)