- How to debug front-end: Console
- Original article by Michał Witkowski
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: lsvih
- Proofread by Raoul1996
Front-end Console debugging tips
Developers inadvertently create bugs along the way. The older the bug, the harder it is to find and fix it. In this series of articles, I’ll try to show you how to debug using the Google Chrome Developer Tools, the Chrome plugin, and WebStorm.
This article will introduce you to the most commonly used debugging tool, Chrome Console. Please enjoy!
Console
Open Chrome Developer Tools:
- From the main menu choose the More Tools menu > Developer Tools.
- Right-click on any element on the page and select Check.
- On a Mac, press Command+Option+I; On Windows and Linux, press Ctrl+Shift+I.
Observe the contents of the Console TAB.
The first line:
- Clearing the Console
Top – By default, the Console context is top. However, it changes when you check the element or use the Chrome plugin context. Here you can change the context of the console execution (the top-level frame of the page).
Filter: Filter the output of the console. You can filter the output by severity level, regular expression, or hide messages from network connections here.
Settings: Hide network – Hides network errors such as 404. Preserve Log – The console will not clear records when a page is refreshed or jumped. Selected Context only – Checked to specify the logging scope of the console based on the context previously Selected by TOP. User Messages only – Hides warnings such as access exceptions generated by browsers. Log XMLHttpRequests – As the name implies, records information generated by XMLHttpRequests. Show timestamps – Displays timestamp information in the console. Autocomplete from History – Chrome keeps a record of all the commands you’ve typed for automatic completion.
Select the appropriate Console API
The console will run the JS code you entered in the context of your application. You can easily view what is stored in the global scope from the console, or you can type directly and see the result of the expression. For example, null === 0.
Console. log – Object reference
By definition, console.log will print the output in the console. In addition, you should also know that console.log keeps references to the objects you display. Take a look at the following code:
var fruits = [{one: 1}, {two: 2}, {three: 3}];
console.log('fruits before modification: ', fruits);
console.log('fruits before modification - stringed: ', JSON.stringify(fruits));
fruits.splice(1);
console.log('fruits after modification: ', fruits);
console.log('fruits after modification - stringed : ', JSON.stringify(fruits))Copy the code
You need to be aware of this when debugging objects or arrays. We can see that the FRUITS array contained 3 objects before it was modified, but has since changed. If you need to see the results at a particular point in time, you can use json.stringify to present the information. However, this approach is not convenient for displaying large objects. A better solution will be introduced later.
Console. log – Sorts object properties
Does JavaScript guarantee the order of object attributes?
4.3.3 Object — ECMAScript 3rd Edition (1999)
An Object is a member of Object, which is an unordered collection of properties, each containing a primitive value, Object, or function. Call functions stored in object properties methods.
But… In ES5 the definition has changed and properties can be ordered – but you still can’t be sure that your object properties can be ordered. Browsers implement ordered attributes in a variety of ways. Run the following code in Chrome and you can see confusing results:
var letters = {
z: 1,
t: 2,
k: 6
};
console.log('fruits', letters);
console.log('fruits - stringify', JSON.stringify(letters));Copy the code
Chrome sorts properties alphabetically. There’s no way to say whether we should like this sort of ordering, but it doesn’t hurt to know what’s going on here.
console.assert(expression, message)
If expression results in false, console. assert will throw an error. Crucially, the Assert function does not stop the evaluated code because of an error. It can help you debug long, sticky code, or find errors in the function itself after many iterations.
function callAssert(a,b) {
console.assert(a === b, 'message: a ! == b ***** a: ' + a +' b:'+b); } callAssert (5, 6); CallAssert (1, 1);Copy the code
console.count(label)
In short, it’s a console.log that counts how many times the same expression has been executed. Everything else is the same.
for(var i =0; i <=3; i++){
console.count(i + ' Can I go with you? ');
console.count('No, no this time');
}Copy the code
As the example above shows, only the exact same expression increases the statistics.
console.table()
Nice debugging function, but I generally don’t bother using it even if it makes me more productive… Don’t be like me. We need to be productive.
var fruits = [
{ name: 'apple', like: true },
{ name: 'pear', like: true },
{ name: 'plum', like: false},]; console.table(fruits);Copy the code
It’s great. First, you can put everything neatly in a table. Second, you will also get console.log results. It works fine in Chrome, but is not guaranteed to work with all browsers.
var fruits = [
{ name: 'apple', like: true },
{ name: 'pear', like: true },
{ name: 'plum', like: false},]; console.table(fruits, ['name'])Copy the code
We can decide whether to display the data content entirely or only certain columns of the entire object. The table is sortable — you can sort the table by clicking on the table header of the column you want to sort.
console.group() / console.groupEnd();
Let’s start with the code this time. Run the following code to see how the console groups.
console.log('iteration');
for(var firstLevel = 0; firstLevel<2; firstLevel++){
console.group('First level: ', firstLevel);
for(var secondLevel = 0; secondLevel<2; secondLevel++){
console.group('Second level: ', secondLevel);
for(var thirdLevel = 0; thirdLevel<2; thirdLevel++){
console.log('This is third level number: ', thirdLevel);
}
console.groupEnd();
}
console.groupEnd();
}Copy the code
It helps you process data better.
console.trace();
Console. trace prints the call stack in the console. This information is very useful if you are building a library or framework.
function func1() {
func2();
}
function func2() {
func3();
}
function func3() {
console.trace();
}
func1();Copy the code
Compare console.log with console.dir
The console. The log ([1, 2]); The console. Dir ([1, 2]);Copy the code
How they are implemented depends on the browser. In the beginning, the specification recommended that dir keep references to objects, while log does not. Log displays a copy of the object. But now, as shown in the figure above, the log also holds references to objects. They present objects in different ways, but we won’t go into that. However, dir can be very useful when debugging HTML objects.
Console. dir prints all properties and methods of an object in detail.
$_ $0 – $4
$_ returns the value of the most recently executed expression. $0 – $4 – references to HTML elements in the last 5 this check element, respectively.
getEventListeners(object)
Returns the event listener registered on the specified DOM element. There is also a more convenient way to set up event listening, which will be covered in the next tutorial.
monitorEvents(DOMElement, [events]) / unmonitorEvents(DOMElement)
You can see the information in the console when any event is triggered on the specified DOM element. Until the corresponding element is unmonitored.
Select elements in the console
Press ESC in the Element TAB to expand the screen.
If the $is not used for another purpose:
$() – equivalent to document.querySelector()**. Does it return the first element matching the CSS selector (e.g. $(‘span’) returns the first span)? () – the equivalent of * * document. QuerySelectorAll () * *. It returns all elements that match the CSS selector as an array.
Copy printed data
Sometimes, when working with data, you might want to make a rough draft, or simply see if two objects are different. It can be cumbersome to select all and then copy, but here’s a handy way to do it.
Right-click on the printed object, select Copy, or Store as Global Element (Store references to the specified element in global scope), and then you can manipulate the stored element in the console.
Anything in the console can be copied by using copy(‘object-name’).
Custom console output styles
Suppose you are developing a library, or a large module for your company or team. It would be nice to highlight some logs in development mode at this point. You can try the following code:
console.log('%c Truly hackers code! ', 'background: #222; color: #bada55');
%d or % I – integer value %f – floating point value %O – expandable DOM element %O – expandable JS object %c – formatted output using CSS
That’s the end of this article, but not the end of Console. You can learn more about it by clicking on the following links:
- Command Line API Reference by Google
- Console API by MDN
- Console API by 2ality
- CSS Selectors
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, React, front-end, back-end, product, design and other fields. If you want to see more high-quality translation, please continue to pay attention to the Project, official Weibo, Zhihu column.