10+ Rarely Used JavaScript Console Methods

Last updated on July 03, 2023
10+ Rarely Used JavaScript Console Methods

You've heard of console.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:

Visual Studio Intellicode recommends console.log() before other methods.

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.

11 Amazing New Features in ES13

11 Amazing New Features in ES13
Get up to speed with all the latest features added in ECMAScript 13 to modernize your JavaScript with shorter and more expressive code.

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.

Using console.log() to log an object to the console

We can view the properties in a Node.js terminal and get colourization too:

Inspecting an object in a terminal running Node.js.

This is an acceptable approach, but the console.table() method offers a more elegant alternative to it:

console.table(cars);
console.table() in the Chrome console
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);
Using console.table() with an array of arrays.

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:

Using the console.assert() method.

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();
Using the console.trace() method.

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.');
Using console.error() in the Chrome dev console.

You won't get this colour separation in Node.js though:

Using console.error() in a Node.js terminal (no colour separation).

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');
Using console.warn() in the Chrome developer console.

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');
Using console.count()

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');
Passing a label to console.count()

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');
Using the console.countReset() method.

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');
Using the console.time(), console.timeLog(), and console.timeEnd() methods.

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();
Using the console.clear() method.

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');
Using the console.group() and console.groupEnd() methods.

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');
Using the console.groupCollapsed() method.

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:

Logging a html element with console.log()
Result of console.log(document.body)

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

Result 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.

Every Crazy Thing JavaScript Does

Every Crazy Thing JavaScript Does
Avoid painful bugs and save valuable time with Every Crazy Thing JavaScript Does, a captivating guide to the subtle caveats and lesser-known parts of JavaScript.

See also