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.
- Console overview
- Use console.log format
- Clear the console
- Count element
- Log more complex objects
- Log different error levels
- Keep logs during navigation
- Group console messages
- Print stack trace
- Calculate the time spent
- Generate CPU configuration file
Console overview
The console toolbar is simple. There is a button to clear the console message, you can also clickcmd-K
In macOS, orctrl-K
On 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.
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.log
The 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)
%s
Format the variable as a string%d
or%i
Format variables as integers%f
Format variables as floating point numbers%o
Can be used to print DOM elements%O
Used to print object representation
example:
console.log('%o, %O', document.body, document.body)
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
)
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:
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)
})
Log more complex objects
console.log
Checking 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])
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.table
It 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'])
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.
Keep logs during navigation
Unless you check allKeep logsIn the console settings:
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()
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()
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()
Print stack trace
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()
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()
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()
Download mine for freeJavaScript beginner's manual
More browser tutorials:
- HTML5 provides some useful tips
- How do I make a CMS-based website work offline
- The complete guide to progressive web applications
- Extract API
- Push API guide
- Channel Messaging API
- Service staff tutorial
- Cache API guide
- Notification API guide
- Dive into IndexedDB
- Selectors API: querySelector and querySelectorAll
- Load JavaScript efficiently with delay and asynchrony
- Document Object Model (DOM)
- Web storage API: local storage and session storage
- Understand how HTTP cookies work
- History API
- WebP image format
- XMLHttpRequest (XHR)
- In-depth SVG tutorial
- What is the data URL
- Roadmap for learning network platforms
- CORS, cross-domain resource sharing
- Network worker
- requestAnimationFrame() guide
- What is Doctype
- Use DevTools console and console API
- Speech Synthesis API
- How to wait for DOM ready event in pure JavaScript
- How to add classes to DOM elements
- How to traverse DOM elements from querySelectorAll
- How to remove classes from DOM elements
- How to check if a DOM element has a class
- How to change the DOM node value
- How to add the click event to the list of DOM elements returned from querySelectorAll
- WebRTC, real-time Web API
- How to get the scroll position of an element in JavaScript
- How to replace DOM elements
- How to only accept images in the input file field
- Why use the preview version of the browser?
- Blob object
- File object
- FileReader object
- FileList object
- ArrayBuffer
- ArrayBufferView
- URL object
- Type array
- DataView object
- BroadcastChannel API
- Streams API
- FormData object
- Navigator object
- How to use the geolocation API
- How to use getUserMedia()
- How to use the drag and drop API
- How to scroll on a web page
- Processing the form in JavaScript
- Keyboard events
- Mouse event
- Touch event
- How to remove all children from DOM element
- How to create HTML attributes using raw Javascript
- How to check if the checkbox is checked using JavaScript?
- How to copy to clipboard using JavaScript
- How to disable buttons using JavaScript
- How to make a page editable in the browser
- How to use URLSearchParams to get query string value in JavaScript
- How to delete all CSS on the page at once
- How to use insertAdjacentHTML
- Safari, warning before exit
- How to add an image to the DOM using JavaScript
- How to reset the table
- How to use Google fonts