10+ Rarely Used JavaScript Console Methods

10+ Rarely Used JavaScript Console Methods

By Ayibatari Ibaba / Last updated on August 25, 2022

You’ve heard ofconsole.log() and probably use it all the time. It’s very popular, and tools like Visual Studio Intellicode usually recommend it before any other console method when typing in an IDE: image-3.png But how many others are you aware of? Did you know they are up to 20? In this article, we’ll explore some of the most useful console methods and their uses for data visualization, debugging, and more.

1. table()

The console.table() method comes in handy when you need to get a visual of a group of objects in your code that can be represented in a tabular form, like an array of objects. Take this list of cars, for example:

const cars = [
  {
    color: 'red',
    age: 4,
    maxSpeed: 120,
  },
  {
    color: 'blue',
    age: 2,
    maxSpeed: 100,
  },
  {
    color: 'yellow',
    age: 3,
    maxSpeed: 160,
  },
];

How would you inspect them in the console? console.log() is a typical approach:

console.log(cars);

In the Chrome developer console, we can inspect various properties of the object we log, to as many hierarchies as we want. image-12.webp We can view the properties in a Node.js terminal and get colourization too: image.webp This is an acceptable approach, but the console.table() method offers a more elegant alternative to it:

console.table(cars);

image-14.webp console.table() in the Chrome console

image-15.webp console.table() in Node.js As the name implies, it presents the data in an easily understandable tabular format, like a spreadsheet. It works for an array of arrays too.

const arr = [
  [1, 3, 5],
  [2, 4, 6],
  [10, 20, 30],
];
console.table(arr);

image-17.webp

2. assert()

Great for debugging purposes, console.assert() takes an assertion and writes an error message to the console if the assertion is false. But if it is true, nothing happens.

const num = 13;
console.assert(num > 10, 'Number must be greater than 10');
console.assert(num > 20, 'Number must be greater than 20');

The first assertion passes because num is greater than 10, so only the second is displayed in the console: image-1.webp

3. trace()

console.trace() helps you output the current stack trace at the location where you call it from. For example:

function a() {
  b();
}

function b() {
  c();
}

function c() {
  console.trace();
}

a();

image-5.webp

4. error()

error() is probably the second most popular Console method. In the Chrome console it displays error messages with a distinctive red colour.

console.error('This is an error message.');
console.log('This is a log message.');

image-7.webp You won’t get this colour separation in Node.js though:

image-8.webp However the messages are written to different locations internally. console.error() writes to the stderr stream, while console.log() writes to the stdout stream. You can access these streams with process.stderr and process.stdout. This is useful for redirecting error messages and informational messages to different files, like we do in the code example below.

const fs = require('fs');

const errorFs = fs.createWriteStream('./error-log.txt');
process.stderr.write = errorFs.write.bind(errorFs);

const infoFs = fs.createWriteStream('./info-log.txt');
process.stdout.write = infoFs.write.bind(infoFs);

console.error('This is an error message.');
console.log('This is a log message.');

When you run this code, the message passed to error() and log() will be outputted to the respective files, instead of the console.

5. warn()

console.warn() outputs a yellow message in the Chrome console, indicating a warning. ```console.warn('This is a warning message');


![image-9.webp](https://cdn.hashnode.com/res/hashnode/image/upload/v1662168894349/m5CyAUFBa.webp align="left") In Node.js the message is written to the stderr stream like **console.error()**.
# 6. count() and countReset()
**console.count()** logs the number of times that the current call to **count()** has been executed. Another useful debugging tool.

function shout(message) { console.count(); return message.toUpperCase() + '!!!'; }

shout('hey'); shout('hi'); shout('hello');


![image-10.webp](https://cdn.hashnode.com/res/hashnode/image/upload/v1662169019766/Z1_e5Vgpu.webp align="left")
The label displayed is default because we didn’t specify a label for. We can do this by passing a string argument to **count()**.

function shout(message) { console.count(message); return message.toUpperCase() + '!!!'; }

shout('hey'); shout('hi'); shout('hello'); shout('hi'); shout('hi'); shout('hello');


![image-11.webp](https://cdn.hashnode.com/res/hashnode/image/upload/v1662169046783/ihHxbNFr8.webp align="left")
Now we have a different count for each message.

The **countReset()** method sets the count for a label back to zero.

function shout(message) { console.count(message); return message.toUpperCase() + '!!!'; }

shout('hi'); shout('hello'); shout('hi'); shout('hi'); shout('hello'); console.countReset('hi'); shout('hi');


![image-12 (1).webp](https://cdn.hashnode.com/res/hashnode/image/upload/v1662169104215/KzRvYQx60.webp align="left")
# 7. time(), timeEnd(), and timeLog()
We can use these methods together to measure how long a particular operation in our program takes.

const arr = [...Array(10)];

const doubles1 = []; console.time('for of'); let i = 0; for (; i < 1000; i++) { for (const item of arr); } console.timeLog('for of'); for (; i < 1000000; i++) { for (const item of arr); } console.timeEnd('for of');

console.time('forEach'); i = 0; for (; i < 1000; i++) { arr.forEach(() => {}); } console.timeLog('forEach'); for (; i < 1000000; i++) { arr.forEach(() => {}); } console.timeEnd('forEach');


![image-13.webp](https://cdn.hashnode.com/res/hashnode/image/upload/v1662169141916/gjDcboNZS.webp align="left")
Here we’re carrying out a performance comparison between the for of and forEach loops.** time()** starts the timer for the operation specified by the label passed to it. **timeLog()** logs the current duration without stopping the timer, and we use it to display the time elapsed after one thousand iterations. **timeEnd()** logs the current duration and stops the timer. We call it after one million iterations have elapsed.

Looks like **forEach() **is faster than for of.
# 8. clear()
**console.clear()** removes clutter from the console by clearing the logs.

console.log('A log message.'); console.clear();


![image-14 (1).webp](https://cdn.hashnode.com/res/hashnode/image/upload/v1662169203377/0Jq-exuHW.webp align="left")
# 9. group(), groupCollapsed(), and groupEnd()
**console.group()** adds a level of indentation to any console messages that come after it. **console.groupEnd() **resets the indentation to the level it was at before the preceding **console.group() **was called.

console.log('This is the outer level'); console.group(); console.log('Level 2'); console.group(); console.log('Level 3'); console.warn('More of level 3'); console.groupEnd(); console.log('Back to level 2'); console.groupEnd(); console.log('Back to the outer level');


![image-16.webp](https://cdn.hashnode.com/res/hashnode/image/upload/v1662169244998/5JfjjxhmO.webp align="left")
**console.groupCollapsed()** creates a group like **console.group()**, but the group is collapsed until the user expands it with the disclosure button next to it.

console.log('This is the outer level'); console.group(); console.log('Level 2'); console.groupCollapsed(); console.log('Level 3 '); console.warn('More of level 3'); console.groupEnd(); console.log('Back to level 2'); console.groupEnd(); console.log('Back to the outer level'); ```

image-15 (1).webp

10. dir()

console.dir() works similarly to console.log() with the exception of logging HTMLElements. console.log() logs an HTMLElement as HTML that we can traverse in the console:

2022-07-02-21_38_25-Clipboard-2.webpResult of console.log(document.body)

But console.dir() will log it as an object, displaying an interactive list of properties:

2022-07-02-21_37_51-Clipboard-1.webpResult of console.dir(document.body)

Conclusion

As you’ve seen in this article, there are plenty of console methods apart from console.log(). Some of them simply spice things up in the console UI with colour and better visualization, and others can serve as powerful tools for debugging and performance testing.