Working with the DevTools Console and the Console API
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.
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.
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])
.
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)
.
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:
1 | const x = 1; |
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])
.
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 }])
.
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.
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.
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:
1 | console.group('Testing the location'); |
You can also create a collapsed group that can be expanded when needed. Use console.groupCollapsed()
instead of console.group()
. For example:
1 | console.groupCollapsed('Testing the location'); |
Nested groups are also possible, allowing you to organize your logs further:
1 | console.group('Main'); |
Print the stack trace
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:
1 | const function2 = () => console.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:
1 | const doSomething = () => console.log('test'); |
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:
1 | const doSomething = () => console.log('test'); |
tags: [“DevTools”, “Console”, “Console API”, “JavaScript debugging”, “Web development”]