Some good debugging techniques of console

Time:2020-6-29

In our daily front-end development, the most frequently used is usingconsole.logPrint out the information we need to debug in the browser console, but most people may not be aware of it, just like me beforeconsoleexceptlogMethods, there are many practical methods, these methods can make our debugging process easier, also more intuitive, more colorful, let’s see what practical methods!

1、console.log()

We use it a lotconsole.logTo print out the value of a variable or an entity object, or pass in multiple variable parameters, which will be printed in the order in which they are passed in

1. Pass in a variable
const a = 1;
console.log(a); // -> 1

2. Pass in an object
const foo = {a: 1};
console.log(foo); // -> {a: 1}

3. Pass in multiple variables
console.log(a, foo); // -> 1 {a: 1}

In addition, it supportsformatted print Function, pass in specificplaceholder To format parameters, common placeholders are as follows:
1) %s: String placeholder
2) %d: integer placeholder
3) %f: floating point placeholder
4) %o: object placeholder (note letterso, not a number0)
5) %c: CSS style placeholder

const string = 'Glory of Kings';
const number = 100;
const float = 9.5;
const obj = {name: 'daji'};

1. % s string placeholder
console.log('I do like %s', string); // -> I do like Golry of Kings.

2. % d integer placeholder
console.log('I won %d times', number); // -> I won 100 times.

3. % f floating point placeholder
console.log('My highest score is %f', float); // -> My highest score is 9.5

4. % O object placeholder
console.log('My favorite hero is %o', obj); // -> My favorite hero is {name: 'daji'}.

5. % C CSS style placeholder
console.log('I do like %c%s', 'padding: 2px 4px;background: orange;color: white;border-radius: 2px;', string);

The placeholder effect of CSS style is as follows:
Some good debugging techniques of console

2、console.warn()

You can use it completelyconsole.warnTo replaceconsole.logMethod, but the premise is that the printed information belongs to the warning level rather than the general information level, so the browser will treat differently when it encounters a warning level information, the most obvious is that there will be a warning icon on the left side of it, and the background color and text color will be different.
Some good debugging techniques of console
Compared with the general information, the warning message will appear on the left side of the above figurewarningPanel, notinfoIn the panel, it also helps us to quickly filter out the warning information from a pile of printed information for easy viewing.

3、console.dir()

In most cases,console.dirThe role of the method andconsole.logThe effects are similar, but with a slight difference.
Some good debugging techniques of console
In the picture above, we can see that,console.logMethod will display the details of the print result completely, butconsole.dirMethod will only print out the object and will not expand the details. Of course, the information you see after clicking is the same as the former.
The only difference is that when we print nodes in HTML documents, there will be totally different representations. For example, we useconsole.logTo printbodylabel:
Some good debugging techniques of console
We can easily see the DOM structure, and mouse over can help us automatically locate the corresponding DOM node. But in some cases, this is not the effect you want to see. Maybe you want to see all the attribute information under the DOM node. Then you can try usingconsole.dirTry it:
Some good debugging techniques of console

4、console.table()

In our project development, we often encounter list data in the form of an array of objects. During debugging, we may useconsole.logMethod to print out these data for viewing, but compared with the former, you can also use a more visual way to print. For example, here are some list data:

const response = [
  {
      id: 1,
      name: 'Marry',
      age: 18,
      sex: 0
  },
  {
     id: 2,
     name: 'John',
     age: 20,
     sex: 1
  }
];

And then we useconsole.logTo print:
Some good debugging techniques of console
We can see that the results we print are not direct enough to give people a clear-cut effect, and then switch to useconsole.tableTo print:
Some good debugging techniques of console
As you can see, our list data is clearly and completely displayed in the table, and at the same timeconsole.tableA second optional parameter is provided to filter the columns that need to be displayed in the table. By default, all columns are displayed.
Some good debugging techniques of console
In the above figure, we add the second parameter, the name of the field to be displayed in the table in the array, so that we can easily filter out the information we don’t need to care about in the result data.

5、console.assert()

assertIn other words, the method receives multiple parameters, the first parameter is the input expression, only if the value of the expression isfalseThe remaining parameters will be output to the console.
Some good debugging techniques of console
The second line in the image above is becausearr.length > 5The value isfalseSo print out the following information. If you need to evaluate whether the current data meets certain conditions in some scenarios, you can use theconsole.assert()Method to view the assertion information in the console.

6、console.trace()

This method is used to display the call path of the current code in the stack in the console. Through this call path, we can easily find the original error point when an error occurs. The example is as follows:

function foo(data) {
  if (data === null) {
    console.trace();
    return [];
  }
  return [data.a, data.b];
}

function bar1(data) {
  return foo(data);
}

function bar2(data) {
  return foo(data);
}

bar1({a: 1, b: 2}); // -> [1, 2]
bar2(null); // -> []

In the code above, we havebar1andbar2Call in functionfooFunction and pass in different parameters, obviouslybar2The function will enter theifStatement and executeconsole.trace()Method, the following is the print results in the console:
Some good debugging techniques of console
You can see a bottom-up call path, and you can quickly determine whether it is in thebar2Improper argument passed in functionnullIt is convenient for us to track the original location of the error.

7、console.count()

This method is equivalent to a counter for recording the number of calls and printing the recorded results to the console. It receives an optional parameterconsole.count(label)labelIndicates the specified label, which will be displayed before the number of calls. An example is as follows:

for (let i = 1;i <= 5;i++) {
    if (!(i % 2)) {
        console.count('even');
    } else {
        console.count('odd');
    }
}

In the code, ifiIf it is even, it will be rightevenCounter, otherwiseoddThe counter counts. After execution, we will see the following list in the console:

odd: 1
even: 1
odd: 2
even: 2
odd: 3

8、console.time() & console.timeEnd()

These two methods are generally used together, and are special functions in JavaScript to track the execution time of programs,console.timeThe method is as the starting time of calculation,console.timeEndIs the end time of the calculation and displays the execution time in the console. If you need to use a calculator in more than one place on a page, you can pass in an optional parameter for the methodlabelTo specify a label that is displayed before the execution time. In the past, we usually used the following methods to calculate the execution time of the program:

const startTime = performance.now();
let sum = 0;
for(let i = 0;i < 100000;i++) {
    sum += i;
}
const diffTime = performance.now() - startTime;
console.log(`Execution time: ${ diffTime }`);

This is a more traditional method, and we can also use itconsole.timeTo achieve:

console.time('sum');
let sum = 0;
for(let i = 0;i < 100000;i++) {
    sum += i;
}
console.timeEnd('sum');

The effect of the console is as follows:
Some good debugging techniques of console
Compared to the first implementation, we did not set any temporary variables and did no calculation.

9、console.group() & console.groupEnd()

As the name implies, data information is grouped, whereconsole.group()Method is used to set the starting position of the group information, and all information after the position will be written to the group,console.groupEnd()Method is used to end the current grouping as follows:

class MyClass {
  constructor() {
    console.group('Constructor');
    console.log('Constructor executed');
    this.init();
    console.groupEnd();
  }

  init() {
    console.group('init');
    console.log('init executed');
    console.groupEnd();
  }
}
const myClass = new MyClass();

The effect of the console is as follows:
Some good debugging techniques of console
The main function of this method is to make the log printed on the console more clear and readable.

10. Browser to editor

In most cases, when we debug the DOM structure or edit some text in the browser, we will edit the DOM nodes in the Elements option of Chrome Developer Tools, but once the nodes are too many, it will be very difficult to increase the debugging process. Here we can make the browser directly convert to browser mode.

document.body.contentEditable = true;

After entering the above code in the console, you can change all content in the browser to editable status, as shown in the following image:

11、Chrome Command Line API

Google’s Chrome command line API includes a handy set of functions for selecting and checking DOM elements, displaying data in a readable format, stopping and starting parsers, and monitoring DOM events.

Note: this API can only be obtained through browser console, and cannot be accessed through web script.

11.1 select DOM element

When we use jQuery, we can use various selectors such as$('#id')and$('.class')To select the matching DOM element, but if we don’t introduce jQuery, we can still do the same in Chrome’s console. The chrome command line API provides the following ways to select DOM elements:

  • $(selector): returns the first reference to the DOM element that matches the specified CSS selector, equivalent todocument.querySelector()Function.
  • $$(selector): returns an array of DOM elements that match the specified CSS selector, equivalent todocument.querySelectorAll()Function.
  • $x(path): returns an array of DOM elements that match the given XPath expression.

Some good debugging techniques of console

$X (‘/ / P [a]) indicates that the<a>All of the elements<p>Element.

11.2 retrieve the value of the last result

In the console, we often do some calculation. In some cases, you may need to track your previous calculation results for later calculation$_Tag can be used to return the value of the most recently evaluated expression, as follows:

1 + 2 + 3 + 4 // -> 10

$_ // -> 10

$_ * $_ // -> 100

Math.sqrt($_) // -> 10

$_ // -> 10

11.3 finding events associated with a specified DOM element

When we need to find all the events associated with an element in the DOM, the console providesgetEventListenersMethod to help us find these associated events.
getEventListeners($('selector'))Returns the event listener registered on the specified DOM element. The return value is an object ofkeyIs the corresponding event type (for exampleclickfocus), object’svalueIs an array containing all event listeners under the corresponding event type. For example, the following lists thedocumentAll event listeners registered on:
Some good debugging techniques of console
If we need to find a specific event listener, we can access it in the following ways:

//EventName represents the corresponding event type
//Index represents the index of the array of event listeners under the event type
getEventListeners($('selector')).eventName[index].listener

//For example, get the first item of the click event listener array under the document
getEventListeners(document).click[0].listener

11.4 monitoring events

If you want to monitor events that are bound to specific elements in the DOM when they are executed, the console providesmonitorEventsMethod to help you monitor some or all of these events with different commands:

  • monitorEvents($('selector')): all events associated with elements that match the selector are monitored and printed to the console when they are triggered. for examplemonitorEvents($('#content'))Will monitoridbycontentAll events associated with the element of.
  • monitorEvents($('selector'), 'eventName'): will monitor a specific event for the element that the selector matches. For example,monitorEvents($('#content'), 'click')Will monitoridbycontentElement associated withclickevent.
  • monitorEvents($('selector'), [eventName1, eventName2, ...]): will monitor some specific events for the elements that the selector matches. Different from the above, the second item can pass in a string array, which contains all the event type names to be monitored, so as to achieve the purpose of user-defined monitoring. for examplemonitorEvents($('#content'), ['click', 'focus'])Will monitoridbycontentElement associated withclickandfocusevent.
  • unmonitorEvents($('selector')): stops monitoring all events associated with elements that match selectors. for exampleunmonitorEvents($('#content'))Monitoring will stopidbycontentAll events associated with the element of.

The effect picture is as follows:
Some good debugging techniques of console

11.5 checking DOM elements

The console providesinspect()Method allows us to examine a DOM element directly from the console.

  • inspect($('selector')): the elements that match the selector are checked and automatically jump to the Elements tab of chrome developer tools. for exampleinspect($('#content'))Will checkidbycontentElements of.

The effect picture is as follows:
Some good debugging techniques of console

communication

This is mainly to share several console debugging skills that I feel good, and I hope that you can help in your front code debugging process. If you feel that the article is good, welcome to pay attention to the official account of the author, and I will start and sort out some dry cargo technology front-end every week, hoping to share with you the learning and progress together.

The article has been updated to GitHub blog. If you think the article is OK, welcome to star!

Your praise is worth more efforts!

Growing up in adversity, only by continuous learning, can we become better ourselves and share with you!

Some good debugging techniques of console