All about the console

13. May, 2022 8 min read Develop

Discovering the console methods

I'm using console.log more than I'd like to admit. Though, many more console methods are available to help in certain situations.

console.assert

The console.assert() method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens.

console.assert('hello' === 'world', 'hello is not the world');
// Assertion failed: hello is not the world

console.assert(typeof 'hello' === 'string', 'hello is not a string');
// will return "undefined" as the assertion does not fail

console.clear

The console.clear() method clears the console if the environment allows it.

console.clear();
// clears the console entries

console.context

The console.context() method lists all the available context methods.

console.context();

// output
Context {dir: ƒ, dirXml: ƒ, table: ƒ, groupEnd: ƒ, clear: ƒ,}
  assert: ƒ assert()
  clear: ƒ clear()
  count: ƒ count()
  countReset: ƒ countReset()
  debug: ƒ debug()
  dir: ƒ dir()
  dirXml: ƒ dirXml()
  error: ƒ error()
  group: ƒ group()
  groupCollapsed: ƒ groupCollapsed()
  groupEnd: ƒ groupEnd()
  info: ƒ info()
  log: ƒ log()
  profile: ƒ profile()
  profileEnd: ƒ profileEnd()
  table: ƒ table()
  time: ƒ time()
  timeEnd: ƒ timeEnd()
  timeLog: ƒ timeLog()
  timeStamp: ƒ timeStamp()
  trace: ƒ trace()
  warn: ƒ warn()
  [[Prototype]]: Object

console.count & .countReset

The console.count() method logs the number of times that this particular call to count() has been called.

[0, 1, 2].forEach(entry => console.count('increment'));
// increment: 1
// increment: 2
// increment: 3

It will continue to count when running the loop again until console.countReset() is called:

[0, 1, 2].forEach(entry => console.count('increment'));
// increment: 1
// increment: 2
// increment: 3

[0, 1, 2].forEach(entry => console.count('increment'));
// increment: 4
// increment: 5
// increment: 6

console.countReset('increment');

[0, 1, 2].forEach(entry => console.count('increment'));
// increment: 1
// increment: 2
// increment: 3

console.debug

The console.debug() method outputs a message to the web console at the “debug” log level. The message is only displayed to the user if the console is configured to display debug output. In most cases, the log level is configured within the console UI. This log level might correspond to the Debug or Verbose log level.

console.debug({ hello: 'world' }, 'debugging my object');

It behaves similar to console.log() and console.info().

console.dir & .dirxml

The method console.dir() displays an interactive list of the properties of the specified JavaScript object. The output is presented as a hierarchical listing with disclosure triangles that let you see the contents of child objects.

In other words, console.dir() is the way to see all the properties of a specified JavaScript object in console by which the developer can easily get the properties of the object.

console.dir(console);
// displays all the methods similar to console.context()

The console.dirxml() method displays an interactive tree of the descendant elements of the specified XML/HTML element. If it is impossible to display as an element, the JavaScript Object view is shown instead. The output is presented as a hierarchical listing of expandable nodes that let you see the contents of child nodes.

console.dirxml(document);
// use dirxml to inspect DOM nodes

console.error

The console.error() method outputs an error message to the Web console.

console.error('This is a custom error message');
// displays the message in red to the console

console.group, .groupCollapsed & .groupEnd

The console.group() method creates a new inline group in the Web console log, causing any subsequent console messages to be indented by an additional level, until console.groupEnd() is called.

console.log('A normal log message');
// lets group the next logs in an accordion style
console.group();
console.log('This is now one level deeper');
console.log('This is now one level deeper');
// even further nesting is possible
console.group();
console.log('And another level deeper');

The console.groupEnd() method exits the current inline group in the Web console. See Using groups in the console in the console documentation for details and examples.

console.log('A normal log message');
// lets group the next logs in an accordion style
console.group();
console.log('This is now one level deeper');
console.log('This is now one level deeper');
// clear the group
console.groupEnd();

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

The console.groupCollapsed() method creates a new inline group in the Web Console. Unlike console.group(), however, the new group is created and collapsed. The user will need to use the disclosure button to expand it, revealing the entries created in the group.

console.log('A normal log message');
// creates the group but collapses it
console.groupCollapsed();
console.log('This is now one level deeper');
console.log('This is now one level deeper');
// you can still combine it with a regular group call
// though the parent is still collapsed
console.group();
console.log('And another level deeper');

console.info

The console.info() method outputs an informational message to the Web console. In Firefox, a small “i” icon is displayed next to these items in the Web console’s log.

console.info('This is an info message');
// well, displays the text :)

console.log

The console.log() method outputs a message to the web console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects.

console.info('Some', 'log', 'message');
// you know this one

console.memory

Related to perfomrnace.memory that displays additional memory information. Be aware that it is not a method call:

console.memory;

// displays additional memory information
MemoryInfo {totalJSHeapSize: 10000000, usedJSHeapSize: 10000000, jsHeapSizeLimit: 3760000000}
  jsHeapSizeLimit: 3760000000
  totalJSHeapSize: 10000000
  usedJSHeapSize: 10000000
  [[Prototype]]: MemoryInfo

console.profile & console.profileEnd

The console.profile() starts recording a performance profile (for example, the Firefox performance tool).

You can optionally supply an argument to name the profile, enabling you to stop only that profile if multiple profiles are recorded. See console.profileEnd() to see how this argument is interpreted.

Be aware that this feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

const profileTest = callback => {
  let counter = 0;
  let interval = setInterval(() => {
    if (counter >= 3) {
      callback();
      clearInterval(interval);
    } else {
      console.log('Working...');
      counter++;
    }
  }, 1000);
};

console.profile('profileTest');
profileTest(() => console.profileEnd());
console.profile();

To view the result in Chrome, select the three dots in the Developer Tools and choose More tools > JavaScript Profiler.

console.table

The console.table() method displays tabular data as a table.

This function takes one mandatory argument data, which must be an array or an object, and one additional optional parameter column.

It logs data as a table. Each element in the array (or enumerable property if data is an object) will be a row in the table.

The first column in the table will be labeled (index). If data is an array, then its values will be the array indices. If data is an object, then its values will be the property names. Note that (in Firefox) console.table is limited to displaying 1000 rows (first row is the labeled index).

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

console.table(new Person('John', 'Smith'));

Or with multiple entries using arrays:

var john = new Person('John', 'Smith');
var jane = new Person('Jane', 'Doe');
var emily = new Person('Emily', 'Jones');

console.table([john, jane, emily]);

console.time, console.timeEnd, console.timeLog & console.timeStamp

The console.time() method starts a timer you can use to track how long an operation takes. You give each timer a unique name, and may have up to 10,000 timers running on a given page. When you call console.timeEnd() with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started.

console.time();
// do something very long
Array.from({ length: 10000000 }).map(n => n * 2);
console.timeEnd();
// wait
// default: 4767.52490234375 ms

The console.timeLog() method logs the current value of a timer previously started by calling console.time() to the console.

The console.timeStamp() method adds a single marker to the browser’s Performance or Waterfall tool. This approach lets you correlate a point in your code with the other events recorded in the timeline, such as layout and paint events.

console.trace

The console.trace() method outputs a stack trace to the Web console.

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

foo();

// traces now by execution:
// bar
// foo
// <anonymous>

console.warn

The console.warn() method outputs a warning message to the Web console.

console.warn('This is your last warning');
// shows an orange marked warning message

That is it

There you have it, all the console methods in a short overview 😎.

‘Till next time!