8 Console API Functions Other Than Console.log()

An in-depth guide to some important console API functions other than console.log

Console API Functions

The Console API’s most commonly used method is undoubtedly console.log. However, it also comes with several other useful methods that can improve our debugging efficiency.

Let’s dive in 🏊 and understand some of the other methods👇

Note: All methods are available in NodeJS as of version 10.0.0 and in almost every major browser.

console.table(data[, properties]) & console.groupEnd(label)👇

While debugging, if there is a complex nested object or an array of objects of the same type, we face difficulty in reading, understanding, and comparing objects.

console.table() is here to rescue us. It presents the data in a clear tabular format. Hence, improving the readability.

The method takes two arguments:

  • data: a collection of data with any type, usually an array of objects.

  • properties: an array of strings of the fields you want to use to display the table.

Let’s understand more with an example:

const data = [
  {
    "id": "0001",
    "type": "donut",
    "name": "Cake",
    "ppu": 0.55,
  },
  {
    "id": "0002",
    "type": "donut",
    "name": "Raised",
    "ppu": 0.55,
  }
];

We have an array of objects data. Let’s see the table method output for our data.

  1. console.table(data)

console.table(data)

  1. console.table(data, ['name'])

console.table(data, ['name'])

Try the same with the nested object and see the output 😄

Notes: You can sort the table by a column by clicking on that column’s label.


console.group(label) & console.groupEnd(label)👇

Sometimes, there may be a scenario where we want to log values within a loop. The best thing to do will be to add a separator at the end of each loop to separate the values of each iteration, but that is still not efficient enough since there are no labels to describe the logs.

With console.group it becomes really simple to properly organize related data and represent each group with a definitive group label while logging to the console.

The methods take an optional argument — label which is the name of the group.

Although it’s not required to pass an argument to console.group(), still, we should do it in order to clarify what values are being grouped together.

We don't have to pass the group name to console.groupEnd() because it will always close the recently created group.

We can also create nested groups if we call console.group() inside an already created group. Here’s a quick example which will help us to understand it better.

console.group() and console.groupEnd()

Notes: Groups created by console.group(label) are initially opened, we can display the group as collapsed from the outset if we call console.groupCollapsed(label). Here’s an example:

onsole.groupCollapsed(label)

console.dir(object) & console.dirxml(object)👇

In the past, the behavior between console.log and console.dir was quite different, particularly when logging object contents, but the newer JavaScript engines have expanded the functionality of console.log so there isn’t much difference from console.dir anymore.

The only difference that I found is when accessing the DOM element in the browser console.

  • console.log prints the element in an HTML-like tree

  • console.dir prints the element in a JSON-like tree from where we can inspect the element DOM properties

Difference between console.log() and console.dir()

In the case of Node.js, the console.dir(obj[, options]) function takes an optional argument which is an object that can have the following keys:

  • showHidden <boolean>. If true then the object's non-enumerable and symbol properties will be shown too. Default: false.

  • depth <number>. Tells how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. To make it recurse indefinitely, pass null. Default: 2.

  • colors <boolean>. If true, then the output will be styled with ANSI color codes. Colors are customizable. Default: false.

Note: If you know more differences, pls feel free to comment down below with examples😊

Calling console.dirxml() on HTML and XML elements or an object is equivalent to calling console.log()

Note: Inside Node.js console.dirxml also calls console.log for its arguments.

Let’s see an example

Difference between console.log() and console.dirxml()

console.profile([, label]) & console.profileEnd([, label])👇

console.profile([,label]) starts to record a performance profile of the CPU and memory usage where it is called (Browser or Node.js).

Each run of the profiler is saved as a separate tab identified by the label passed as an argument.

Remember to end profiling using the console.profileEnd(label).

Let’s understand by an example:

This creates a JavaScript profiler with a name test1 and starts recording the performance of the browser (assuming it ran in browser). To see the recorded performance in the case of the Chrome browser.

console.profile([, label]) & console.profileEnd([, label])

Note: If you don’t see JavaScript profiler panel in the developer tools then follow this —Click three dots menu (in the top right corner) ⋮-> More tools -> JavaScript Profiler.

In the case of Node.js, the method does not display anything unless used in the inspector. Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector.

If console.profileEnd() method is called without a label, the most recently started profile is stopped.

Note: This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web.


console.time([, label]) & console.timeEnd([, label])👇

console.time() starts a timer that can be used to compute the duration of an operation. console.timeEnd() stops the timer and print total run time in milliseconds.

Timers are identified by a unique label and if not specified, the timeEnd will take the most recent time function and stop it.

They are mostly used when you need to do a performance check of a piece of code. You can also pass a string to time and timeEnd and it will start another timer of that name.

Let’s understand with a small example

console.time([, label]) & console.timeEnd([, label])

The time it took for the loop to finish is 0.01708984375ms.

Note: Check out this performance analysis open-source code solely made using the above two functions.

console.count([, label]) & console.countReset([, label])👇

console.count([,label]) places a counter on the label passed as an argument. Each time it is called, the value of the counter is increased. A label together with a number is displayed in the debugging console and if label is not passed, console.count() will log the number of times it has been invoked at that time with the default as a label like this:

[label]: X    //when label is passed
default: X    //when label is not passed

console.countReset() will reset the value of count and if it is used with the parameter label then it will reset the value of the count of that particular label.

Here’s an example to get a better understanding of these methods.

console.count([, label]) & console.countReset([, label])

In the above example, when we reset the value of the counter using console.countReset()and again made a call to console.count()method, we see that it return the counter 1 as it called once.

Also, notice the difference between the call to these methods with or without a label. 🌟

console.assert(expression, message)👇

The method is used to run simple assertion tests. It takes two required arguments:

  • expression: A boolean expression.

  • message: A string or an object which is written to the console.

Note: If an expression is false, it will write a message to the console and throw an exception. If it is true then it will do nothing.

console.assert(expression, message)

console.trace([,data])👇

Sometimes, while debugging the complex function calls, we get stuck in the situation of detecting the callable function and its parameter values. This is whereconsole.trace() comes into picture and prints the stack trace of callable functions to the console from the point it is called.

Note: An instance where this can be used is tracing the stack when an exception is thrown in Node.js or when we are debugging a function in the browser.

Too many outputs?

Just clear all the content using console.clear() 😃

If you liked the article, feel free to share it and help others find it!

Get yourself added to our 2500+ people subscriber family to learn and grow more and please hit the share button on this article to share with your co-workers, friends, and others.

Check out articles on Javascript, Angular, Node.js, Vue.js

For more articles stay tuned to overflowjs.com

Thank you!

Email

About Deepak Gupta

Deepak is profound programmer and financial educator in India. He has co-founded couple of startup from scratch and worked in more than 12 startup and big corporate with different roles.

Owing to his interest, he has been writing blogs regarding JavaScript and other framework to help people starting with it. Also, love to educate people about trading and cryptoworld in his free time.

Subscribe to our email list

More Tags Of Your Interest