Use DevTools console and console API

Each browser provides a console that allows you to interact with the Web platform API and can also enable you to gain insight into the code by printing messages generated by the JavaScript code running on the page

Each browser provides a console that allows you to communicate withWeb platform APIAnd by printing the message generated by you, you can get an in-depth understanding of the codeJavaScriptThe code runs in the page.

The browser console

Console overview

The console toolbar is simple. There is a button to clear the console message, you can also clickcmd-KIn macOS, orctrl-KOn Windows, the second button activates the filtering sidebar, allowing you to filter by text or message type (for example, error, warning, information, log, or debug message).

You can also choose to hide messages generated by the network and focus only on JavaScript log messages.

Filtering console messages

The console is not only a place where you can view messages, but also the best way to interact with JavaScript code (and many DOMs). Or, just get the information from the page.

Let's enter the first message. Note>, let's click here and type

console.log('test')

The console acts asreplace, Which means a read-evaluate-print cycle. In short, it explains our JavaScript code and outputs some content.

Use console.log format

As you can see,console.log('test')Print "test" in the console.

useconsole.logThe code in the JavaScript code can help you debug, for example by printing a static string, but you can also pass it a variable, which can be a JavaScript native type (such as an integer) or an object.

You can pass multiple variables toconsole.log, E.g:

console.log('test1', 'test2')

We can also format beautiful phrases by passing variables and format specifiers.

E.g:

console.log('My %s has %d years', 'cat', 2)
  • %sFormat the variable as a string
  • %dor%iFormat variables as integers
  • %fFormat variables as floating point numbers
  • %oCan be used to print DOM elements
  • %OUsed to print object representation

example:

console.log('%o, %O', document.body, document.body)

Print objects in the console

Another useful format specifier is%c, It allows passing CSS to format strings. E.g:

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 using various input methods.

The first method is to clickClear the console logButtons on the console toolbar.

The second method is to enterconsole.clear()In the console, or in yourJavaScript functionRun in your application/website.

You can also enterclear().

The third method is through keyboard shortcuts, which arecmd-k(Mac) orctrl + l(win)

Count element

console.count()It is a convenient way.

Take the following code:

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?'
)

What happens is that the count will count the number of times the string is printed, and print the count next to it:

Counting the times a string is printed

You can count only apples and oranges:

const oranges = ['orange', 'orange']
const apples = ['just one apple']
oranges.forEach(fruit => {
  console.count(fruit)
})
apples.forEach(fruit => {
  console.count(fruit)
})

Counting the fruits

Log more complex objects

console.logChecking the variables is amazing. You can also pass it an object, and it will try to print it to you in a readable manner. In most cases, this means that it will print the string representation of the object.

For example try

console.log([1, 2])

Another option for printing objects is to useconsole.dir:

console.dir([1, 2])

As you can see, this method prints the variable in a JSON-like representation, so you can check all its properties.

The same function of console.dir output can be realized by executing

console.log('%O', [1, 2])

Console logging with dir

Of course, which one to use depends on what you need to debug, and one of the two can do the best for you.

Another function isconsole.table()Print a beautiful table.

We only need to pass it an array of elements, and it will print each array item in a new line.

E.g

console.table([[1, 2], ['x', 'y']])

Or you can set the column name by passing the object literal (instead of an array), so it will use the object property as the column name

console.table([
  { x: 1, y: 2, z: 3 },
  { x: 'First column', y: 'Second column', z: null }
])

Console logging with table

console.tableIt can also be more powerful, and if you pass it an object literal that contains an object, and pass it an array with column names, it will print the table with the row index obtained from the object literal. E.g:

const shoppingCart = {}
shoppingCart.firstItem = { color: 'black', size: 'L' }
shoppingCart.secondItem = { color: 'red', size: 'L' }
shoppingCart.thirdItem = { color: 'white', size: 'M' }
console.table(shoppingCart, ['color', 'size'])

Filtering console logging

Log different error levels

As we have seen, console.log is very suitable for printing messages in the console.

Now, we will discover three convenient methods that are helpful for debugging because they implicitly indicate various levels of errors.

First,console.info()

As you can see, there is a small "i" printed next to it, indicating that the log message is just information.

second,console.warn()

Print a yellow exclamation mark.

If you activate the console filter toolbar, you can see that the console allows you to filter messages based on type, so it is really convenient to distinguish messages, because for example, if we click "Warning" now, all non-warning printed messages will be hide.

The third function isconsole.error()

This is a bit different from other methods, because in addition to printing a red X to clearly indicate that there is an error, we also have a complete stack trace of the function that caused the error, so we can try to fix it.

Logging stack trace

Keep logs during navigation

Unless you check allKeep logsIn the console settings:

Preserve log during navigation

Group console messages

The size of console messages may increase, and the noise may be overwhelming when you try to debug errors.

To limit this problem, the console API provides a convenient function: grouping console messages.

Let's make an example first.

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

As you can see, the console created a group and we have Log messages.

You can perform the same operation, but output a collapsed message, which you can open as needed to further limit the noise:

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

Happily, these groups can be nested, so you can end up

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

In some cases, it is useful to print the call stack trace of the function, perhaps to answer the questionHow did you get to that part of the code?

you can use itconsole.trace():

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

Print stack trace

Calculate the time spent

You can easily calculate the time required for a function to run using the following methods:time()withtimeEnd()

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 CPU configuration file

DevTools allows you to analyze the CPU profile performance of any function.

You can start it manually, but the most accurate method is to wrap the content to be monitored inprofile()withprofileEnd()command. They are similar totime()withtimeEnd()In addition to them, not only can they measure time, they can also create more detailed reports.

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

Generate a CPU profile

Download mine for freeJavaScript beginner's manual


More browser tutorials: