DEV Community

Thomas Betous
Thomas Betous

Posted on

Javascript console API : 9 helpful tips

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

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 : It will display general message in the console
  • debug : It will display debug message in the console
  • info : It will display informative message in the console
  • warn : It will display a warning message in the 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 and each of these will pull the next argument in order to format the string.

Let's see an example :

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

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

Chrome : console example with log filter (exclude warning)

Alt Firefox : console example with log filter

Firefox : console example with log filter (exclude warning)

Note that the logging level of messages produce with log method can be different between browsers. For example Chrome will not make differences between log and 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 : Creates a new inline group, indenting all following output by another level. To move back out a level, call groupEnd().
  • groupCollapsed : Creates a new inline group, indenting all following output by another level. However, unlike 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().
  • groupEnd : Exits the current inline group.

Here is a trivial example :

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

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

Alt Chrome : Group log messages

Chrome : Group log messages

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 method, the group is automatically unfold
  • When you use 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 and 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 : 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 and each of these will pull the next argument in order to format the string.
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
Enter fullscreen mode Exit fullscreen mode

Here is the result you will have in Chrome :

Alt Chrome : console.assert result

Chrome : console.assert result

With this syntax you can write your debug code with a faster and easier way than a console.error wrapped in a condition block.

Finally, if you use nodeJS, you should know that even if assert method works well, it sends log messages to stdout. It is recommended to use assertion API that provides more methods and sends log messages to stderr by throwing 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 : Log the number of times this line has been called with the given label.
  • countReset : Resets the value of the counter with the given label.

The 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 :

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

Here is the result you will have in Chrome :

Alt Chrome : console.count result

Chrome : console.count result

⏱️ 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 : Starts a timer with a name specified as an input parameter.
  • timeLog : Logs the value of the specified timer to the console.
  • timeEnd : Stops the specified timer and logs the elapsed timein seconds since it started.

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

console.time('test')
setTimeout(() => {
   console.timeLog('test')
   setTimeout(() => {
       console.timeEnd('test')  
   }, 3000)
}, 3000)
Enter fullscreen mode Exit fullscreen mode

Here is the result in Chrome :

Alt Chrome : Time the execution

Chrome : Time the execution

📍 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 : Adds a marker to the browser's performance tools.
console.timeStamp('test')
Enter fullscreen mode Exit fullscreen mode

Here is the result in Firefox :

Alt Firefox Performance tool: console.timeStamp result

Firefox Performance tool: console.timeStamp result with string 'test'

✨ 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 : Displays tabular data as a table

Here is an example :

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

Here is the result in Chrome :

Alt Chrome : console.table result

Chrome : console.table result

🔎 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 : Outputs a stack trace.

Here is how to use it :

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

foo();
Enter fullscreen mode Exit fullscreen mode

Here is the result in Chrome :

Alt Chrome : console.trace result

Chrome : console.trace result

🧼 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 : Clear the console.

Here is how to use it :

// This will clear the console
console.clear()
Enter fullscreen mode Exit fullscreen mode

Here is the result in Chrome :

Alt Chrome : console.clear result

Chrome : console.clear result

🎉 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
  • Share this post !

Thank you for showing interest and reading this 🎉

Top comments (7)

Collapse
 
stegriff profile image
Ste Griffiths

Great tips, my favourite is console.trace() ... I'd seen that technique in a tweet ages ago and forgot what it was, so thanks for the reminder.

Collapse
 
tbetous profile image
Thomas Betous

You're welcome ! Thanks for reading ! :)

Collapse
 
tam360 profile image
Mirza

console.table() is awesome!!!!!

Collapse
 
pamprog profile image
PamProg

Thanks !
Finally an original post about Javascript that is REALLY not well known :)

Collapse
 
olsard profile image
olsard

Great, thank you!

Collapse
 
markprovan profile image
Mark Provan • Edited

Thanks for this! I didn’t know about assert. console.table can be super useful too.

Collapse
 
tbetous profile image
Thomas Betous

Thanks for reading ! I am glad this will help you !