Every browser provides a console that allows you to interact with the Web Platform APIs and view messages generated by your JavaScript code. In this article, we will explore how to work with the DevTools console and the Console API to improve your debugging and development process.

The browser console

Overview of the console

The console toolbar provides several useful features. There is a button to clear the console messages, which can also be done by clicking cmd-K in macOS or ctrl-K on Windows. Another button activates a filtering sidebar that allows you to filter messages by text or type, such as error, warning, info, log, or debug messages. You can also choose to hide network-generated messages and focus only on JavaScript log messages.

Filtering console messages

The console is not just a place to view messages, but it is also an interactive space to work with JavaScript code and DOM manipulation. Let’s type our first message: console.log('test'). The console acts as a REPL (read–eval–print loop), interpreting our JavaScript code and printing the result.

Use console.log formatting

The console.log method is commonly used for debugging by printing static strings or passing variables, which can be JavaScript native types or objects. You can pass multiple variables to console.log like this: console.log('test1', 'test2'). Additionally, you can format phrases by using variables and format specifiers. For example: console.log('My %s has %d years', 'cat', 2). Here, %s formats a variable as a string, %d or %i formats a variable as an integer, %f formats a variable as a floating-point number, %o prints a DOM element, and %O prints an object representation. You can print objects using console.log, console.dir, or console.log('%O', [1, 2]).

Print objects in the console

The %c format specifier allows you to pass CSS to format a string. For example: console.log('%c My %s has %d years', 'color: yellow; background:black; font-size: 16pt', 'cat', 2).

Format in the console using CSS

Clear the console

There are three ways to clear the console. First, you can click the “Clear Console Log” button on the console toolbar. Second, you can type console.clear() inside the console or in your JavaScript code. Lastly, you can use the keyboard shortcut cmd-k (mac) or ctrl + l (Win).

Counting elements

The console.count() method is useful for counting the number of times a piece of code is executed. For example:

const x = 1;
const y = 2;
const z = 3;
console.count('The value of x is ' + x + ' and has been checked .. how many times?');
console.count('The value of x is ' + x + ' and has been checked .. how many times?');
console.count('The value of y is ' + y + ' and has been checked .. how many times?');

Counting the times a string is printed

Log more complex objects

The console.log method can print variables, including objects, in a readable way. Another option is to use the console.dir method, which prints a variable in a JSON-like representation. For example: console.log([1, 2]), console.dir([1, 2]), or console.log('%O', [1, 2]).

Console logging with dir

You can also use the console.table() method to print arrays or objects in a tabular format. For example: console.table([[1, 2], ['x', 'y']]) or console.table([{ x: 1, y: 2, z: 3 }, { x: 'First column', y: 'Second column', z: null }]).

Console logging with table

Logging different error levels

Besides console.log, there are three additional methods that implicitly indicate various levels of error. The console.info() method prints an information message with a little ‘i’ icon. The console.warn() method prints a warning message with a yellow exclamation point. The console.error() method prints an error message with a red X and provides a stack trace to help identify the source of the error.

Logging stack trace

Preserve logs during navigation

By default, console messages are cleared on every page navigation. However, you can preserve the logs by checking the “Preserve log” option in the console settings.

Preserve log during navigation

Grouping console messages

To reduce noise and make debugging easier, the Console API offers the ability to group console messages. You can create a group using console.group() and end it with console.groupEnd(). For example:

console.group('Testing the location');
console.log('Location hash', location.hash);
console.log('Location hostname', location.hostname);
console.log('Location protocol', location.protocol);
console.groupEnd();

Logging groups

You can also create a collapsed group that can be expanded when needed. Use console.groupCollapsed() instead of console.group(). For example:

console.groupCollapsed('Testing the location');
console.log('Location hash', location.hash);
console.log('Location hostname', location.hostname);
console.log('Location protocol', location.protocol);
console.groupEnd();

Another example of logging in groups

Nested groups are also possible, allowing you to organize your logs further:

console.group('Main');
console.log('Test');
console.group('1');
console.log('1 text');
console.group('1a');
console.log('1a text');
console.groupEnd();
console.groupCollapsed('1b');
console.log('1b text');
console.groupEnd();
console.groupEnd();

Nesting groups

To answer the question, “how did you reach that part of the code?”, you can print the call stack trace of a function using console.trace(). For example:

const function2 = () => console.trace();
const function1 = () => function2();
function1();

Print stack trace

Calculate the time spent

You can measure the time it takes for a function to run using console.time() and console.timeEnd(). For example:

const doSomething = () => console.log('test');
const measureDoingSomething = () => {
  console.time('doSomething()');
  // do something, and measure the time it takes
  doSomething();
  console.timeEnd('doSomething()');
};
measureDoingSomething();

Use console time

Generate a CPU profile

The DevTools allow you to analyze the CPU profile performance of any function. You can use console.profile() and console.profileEnd() to create a detailed report. For example:

const doSomething = () => console.log('test');
const measureDoingSomething = () => {
  console.profile('doSomething()');
  // do something, and measure its performance
  doSomething();
  console.profileEnd();
};
measureDoingSomething();

Generate a CPU profile