The console method is console.log(). However, there are many methods related to console, involving a wide range of debugging panel related content, thorough understanding of them and reasonable use in the project, will help us better development and debugging.

Let’s print out the console and see what other magical methods it has:

If you haven’t read About Console, are you surprised that there are so many ways to use Console? Starting with the simplest method, console.log, let’s look at the other methods and the debugging techniques involved.

1.console.log() Prints the content. This method is too familiar with that, usually is also used most perhaps also is this one!! Let’s skip the basic usage and focus on the placeholder for console.log(). There are five types of placeholders, which are:

  1. % s string
  2. %d or % I integer
  3. % f floating point number
  4. Link to %o object
  5. %c CSS format string

If a placeholder is used in the first argument of the method, the following arguments are replaced in turn.

const name = 'chinaBerg';
const age = 88;
const money = 12.88;
const obj = {
    status: 'Very active'
}

console.log('My name is %s, %d years old, have %f yuan, status: % O', name, age, money, obj.status, 'Print another sentence')Copy the code

Google print results:



You can see that the arguments we use later replace the previous placeholders, a bit like our simplified string concatenation. For example, in our es5 string concatenation:

console.log('my name is' +  name + ' ,' + age +'Age, have' + money + '元')Copy the code

Of course, ES6 already has stronger string templates:

The console. The log (` my name${name}.${age}Years old, and have${money}Yuan `);Copy the code

Concatenated strings can also be mixed:

// For example, here demonstrates: The first argument is the concatenated string, and the second argument inserts the string's floating point console.log('my name is' +  name + ' ,' + age +'Years old, with %f yuan',  money)Copy the code

However, in the es6 string template, only the %c placeholder can be used, other placeholders are not effective.

// Note that the string template is inserted at the end of %f console.log(' my name${name}.${age}%f yuan ', 12.88);Copy the code



The %c placeholder is a little interesting:

const css1 = 'font-size: 22px; font-weight: bold';
const css2 = 'border: 1px solid green';
const css3 = 'color: #fff; background: #f00'; // Fill in the placeholder console.log('%c %s + %s = %s', css1, 1, 2, 3); // Insert the %c placeholder console.log() in string concatenation'%c My name is' + name + This year, ' ' + age + ', ', css2); // ES6 string template insert %c placeholder console.log(' %c I call${name}.${age}Years old, %f yuan ', CSS3);Copy the code

Google Print effect:



You can see that the printed content has been added with our styles.

———————————————————————

2. Similar to console.log(), there are console.info() and console.debug(). In fact, these three functions are the same, but there are some differences, the following is the specific introduction of these three methods.

Take a look at how these three lines of code look when printed on Google, Firefox, and Ie:

console.log('I'm printed out of console.log()');

console.info('I'm printed out of console.info()');

console.debug('Console.debug () prints out')Copy the code
Google Chrome Console print effect:

Firefox Console:



Ie Console:



As can be seen from the results:

  • console.log()Method, no matter which browser, the print effect is the same.

  • console.info()Method, ie did not print it, ie does not support this property. On Google and Firefox, however, there is a slight difference: the printed result is the same, but on firefox’s console, a small symbol like I is added before the printed result.

  • console.debug()Method, Google and Opera are not supported, IE and Firefox are supported.

So, since all three methods are basically the same, if we just want to print some content, we should just use console.log(). Of course, this doesn’t stop you from using Firefox to debug! However, if some printout of your code base needs to be shown to other developers, it is better to use compatibility.

———————————————————————

3.console.clear() clears the console print and returns the cursor to the first line.



There’s nothing to say about this property, it’s the same as clicking the clear button on the console.

———————————————————————


4. Console. assert(expression [,arg1, arg2… argn]) prints the assertion.

The first argument is an expression that determines whether to print the assertion, and subsequent arguments are printed only if the expression has a value of falsy:

const arr = [1, 2, 3]; Console. assert(arr[0] === 2, arr[0] === 2,'arr[0] is not equal to 2');Copy the code

Google Console prints below:



If there are no arguments, the following string is printed by default:

Other points to note:


  • The client’sconsole.assert()Printing an assertion does not block subsequent code execution, but prints your content to the console if the assert expression is false.

  • And in thenode.js, an assertion with a false value will result in aAssertionErrorIs thrown, causing code execution to be interrupted. There is a difference between the two.

———————————————————————

5. Console.count () Prints the count. Output how many times it was called.

Pass an argument as a count hint:

for (let i = 0; i < 10; i++) {
    console.count('I've been called');
}Copy the code

Google Console:



Simple modification:

for (leti = 0; i < 10; I++) {console.count(' I am${i}I was called '); }Copy the code

Print effect:



Write to the console the number of times count() was called on the same line with the same label.

That is, if you pass different values to count(), then count separately.

Here’s another simple example:

function fun (name) {
    console.count(name)
}
fun('millet');
fun('xiao gang');
fun('millet');Copy the code

Effect:



Therefore, even with the same function, we can clearly know that Xiaomi has been called twice and Xiaogang has been called once.

If no argument is passed, the default count prompt label is the default string:

for (leti = 0; i < 10; I++) {// count() did not pass the prompt label console.count(); }Copy the code

The effect is as follows:



In some loops, if we want to know how many times a function or variable has been executed or called, we can use the console.count() method. By passing the prompt tag, we can see how many times a function has been called in different cases, which can help us locate the error message.

———————————————————————

6. Console.time () and console.timeend () print the timing. It is used to track the duration of an operation. Each timer must have a unique name, and the time() argument must have the same name as the timeEnd() argument. There can be no parameters, the default timing prompt is default:

// Start the timer immediately console.time() // somethingfor (leti = 0; i < 10000; I++) {// some action} // immediately end the timer and output the result console.timeend ()Copy the code

The console print effect is as follows:



Pass timer prompt:

// Start the timer immediately console.time('time') // Some operationsfor (leti = 0; i < 10000; I++) {// some operation} // immediately end the timer and output the result console.timeend ('time')Copy the code

The console print effect is as follows:



Note:

  • Up to 10,000 timers can run simultaneously on a page
  • This method does not return the settlement results to JS, but simply prints them on the console. You cannot use this method in JS as a regular timer or as part of the performance collector.


7.console.dir() prints the specified object in JavaScript. If the object being logged is an HTML element, its attributes in DOM form are printed.

Print an object:

// an object const obj = {name:'So-and-so slag',
    age: 22,
    sex: 'male'} // dir prints console.dir(obj); //logPrint the console. The log (obj);Copy the code

Google Console Effects:



Console.log () has the same effect as console.dir() for objects, json, etc.

But if you print a DOM element:

// dir Print console.dir(document.body); //logPrint the console. The log (document. The body)Copy the code
  • console.dir()All properties and events of the DOM are printed:

  • Console.log () prints the DOM:

If one day you’re coding and you can’t remember a dom method, you can simply console. Dir () without having to look at the data.

———————————————————————

8. Console. dirXML (object) Output the XML representation of the child element of object if possible, or its JavaScript representation otherwise. Calling console.dirxml() on HTML and XML elements is equivalent to calling console.log().

———————————————————————

9. Console.group () + console.groupend () groups console output.

Print the printed information in groups and can be expanded and collapsed. This may be useful in exporting large amounts of data.

// Form of console.groupend () + console.groupend (), default is console.group('Group one');
console.log('html')
console.dir({ type: 'front end'}),
console.groupEnd('Group one') // console.group() + console.groupend () Defaults to expanded console.group()'Group 2');
console.log('php')
console.dir({ type: 'background'}),
console.groupEnd('Group 2')Copy the code

Google Print effect:



———————————————————————

10. Console.table () can print complex types of data such as arrays, objects, and so on as tables.

Print a simple array:

const arr = ['a'.'b'];
			
console.table(arr)Copy the code

Print a complex array:

const arr = [
    {
        name: 'Ming',
        age: 22,
        likes: ['dancing'.'the Internet']
    },
    {
        name: 'xiao gang',
        age: 23,
        likes: ['lu code'.'Computer']}]; console.table(arr)Copy the code



Print object:

const obj = {
    name: 'Ming',
    age: 22,
    likes: [
        {
            a: 1,
            b: 2
        },
        {
            a: 3,
            b: 4
        },
    ]
}
				
console.table(obj)Copy the code



With the result printed by console.table(), we can visually see the composition of the data.

———————————————————————

11. the path in the console.trace() stack to call this method.

If you want to know the call path of a function, you can write this method inside the function to trace the call path of the function.

function test(name) {console.trace(' called here${name}`)}function doSome (name) {
    test(name);
}
				
doSome('cui flower');Copy the code

Google Console prints below:



All the stack locations in js where test() was called are printed here. From top to bottom, the innermost call goes all the way to the outermost call. Usually when we use a third-party library, if we don’t write it right, we’ll see our error message in the console, and we’ll print out the stack for the wrong location like this.

———————————————————————

12.console.warn() Prints a warning message

console.warn('I am a warning')Copy the code

Google printed the results as follows:



The print will have a yellow background and an exclamation mark icon in front of it.

Default is folded, click to expand, list the warning location of the stack information, click the stack location can be corresponding to open the warning location code. There is nothing to say about the use of this, and if you need to print a warning message, this method is fine.

———————————————————————

13.console.error() Print error.

console.error('I've got an error here, I'll tell the user.')
Copy the code

Google printed the results as follows:

This method is mainly used for printing errors, and the style of the printed result is shown in the figure above. There’s nothing to say, but if you’re developing third-party libraries, you can use them. But the way the throw throws errors is also used a lot.

———————————————————————

14. Console.profile () and console.profileend () create a new performance analyzer (based on CPU usage). A powerful tool for functional performance analysis.

We already know that console.time() and console.timeend () tell us how long a piece of code runs. However, if we need to analyze more complex JS logic to find performance bottlenecks, continuing with the console.time() method means we have to insert a lot of this method, which is obviously clumsy and unacceptable.

Instead of tuning JavaScript programs with complex logic, console.profile() and console.profileend () create new performance profilers.

The usage is the same as for time, starting with console.profile() and ending with console.profileend (). You need to pass a parameter as the tag, or in a more mundane way, give the profiler a name. Looking at the following code, we test the time taken to write several different for loops:

// Create an array with 10 million members of 1letarr = new Array(10000000).fill(1); / / the firstforCircular writingfunction fun1 () {
    for (leti = 0, len = arr.length; i < len; I++) {}} // the secondforCircular writingfunction fun2 () {
    for (leti = arr.length; i --; ) {} fun1(); } // The thirdforCircular writingfunction fun3 () {
    for (leti = 0, item; item = arr[i++]; ) {}} // Execute three functionsfunction fun() { fun1(); fun2(); fun3(); } // Start a performance analyzer immediately console.profile('Test for loop');
fun();
//
console.profileEnd('Test for loop');
Copy the code

Run the above program and open the Google Console to see:

Well, that’s right, printed two sentences, performance analyzer on and off. Nani ~ said the performance analyzer?? Little fist is going to hit your chest!!

Don’t worry, the performance Profiler is not here, it’s in the javascript Profiler panel.



Click on the javascript Profiler panel to see the performance Profiler. If you don’t have the panel shown in the red box above, click the three dots on the right and select them from the drop-down menuMore tools -> JavaScript ProfilerOption, you can add that option to the red box above. Then click on the panel to enter the corresponding content:

As you can see, with the performance analysis just done, there is a clear picture of how long each function takes to execute. Then let’s click on each function to see what happens:

I’ve highlighted it here:

  • At 1, Self Time means that the current function itself takes Time to run. What does that mean? That is, the execution time of the current function itself, excluding the running time of other functions called by the current function.
  • Where, Total Time indicates the Total running Time of the current function, including its own running Time + the execution Time of other functions called within the function.
  • The Function column, as shown in the fun1 column opened in the figure above, expands fun1 to include fun and fun2. This refers to the time taken for fun1 to be called and executed in fun2 and fun1. We know from the code that fun1 was actually called once in both fun and fun. so here’s how long it takes for fun to be called at both places.
  • At the far right of each function line, there is a stack position. Click to enter the file location of the function in the Resouce panel.

If you care about the execution time of fun1, you can select the line fun1 and click on the eye icon. It will automatically show you only fun1 information:



  • Select the function line and click the eye to display the current function.
  • Select function and, if you click the x, the current function line will be deleted.
  • If you want to return to the panel of all the above function rows, click the refresh button shown in the image above. Or delete the function line can be restored as shown in the figure above.
  • The above three buttons can only be clicked when the color becomes darker, the eye and x can only be clicked when the function line is selected, and the refresh button can be clicked after entering or deleting the function line.

Another thing I didn’t explain is that this is the default way of presenting data: Heavy(Bottom Up), that is, all the functions that are executed are listed in descending order, with the time-consuming functions at the top and the non-time-consuming functions at the Bottom. However, he has two other methods (Chart and Tree), as shown below:



Let’s start with Tree data analysis. Let’s switch to Tree data analysis and see the following figure:

When each function line is opened, the function called by that function is displayed. The way the data analysis is presented is that the outermost function is shown first, then all functions called by that function are shown, and so on. Each line shows how long the function takes to execute. The other operations are as above.

Finally, let’s talk about the Chart method. Chart is a graph that shows the performance of functions after they are run. You can see the time node when each function starts running, as shown in the figure below:

It is roughly divided into the upper and lower parts. The blue area in the upper part is the general trend chart of CPU usage. You can clearly see the CPU usage of each time node. The bottom half is the node at which each function started.

If you click the above part of the blue area, you can also view the function operation of the current event in a finer granularity (the current time node is divided into finer dynamics), as shown in the figure below:



When you move the mouse to a function, you can also see the running time of the current function, as shown in the figure below:



The establishment of console.profile() and console.profileend () function performance analysers brings us great convenience in analyzing function performance, which is very helpful in detecting program bottlenecks. Google has created such a great debugging tool for us, so make sure you use it when you need it.

———————————————————————

15. Console. timeStamp(‘ Event information ‘), insert an entry to add an event during session recording in the Performance(formerly called Timeline) Performance panel.

Speaking of the console.timestamp () method, this method will be used when we do performance debugging. The first thing to mention about this method is the Performance panel, because the results printed by this method need to be viewed in the debug panel. To be precise, this method is debug in conjunction with the Performance panel:



As shown above, in the Perdormance panel, we can analyze the performance of the current page and get the results of the analysis of events related to page loading and user interaction. About the content of Performance, if carefully said, the content is relatively large. For the time being, only the console.timeStamp method is covered here. This piece can be taken out and analyzed and recorded separately later.

Console. timeStamp can write an event on the timeline:

// Some other operationsfor (leti = 0; i < 10000; I ++) {} // First event inserted during recording session console.timestamp ('The first cycle is over.') // some other operationsfor (leti = 0; i < 10000; I ++) {} // Insert the second event console.timestamp ('Loop 2 is over.')Copy the code

After recording the session, we can see that a prompt box pops up on the yellow vertical line at the top left of the red box in the following figure, with Timestamp message: ‘The first loop is over’ and the time node when the event was inserted.


———————————————————————

16. Console.marktimeline () is the same as console.timestamp (), which was written before console.timestamp () and is obsolete. Not much said.

———————————————————————

17. Console. timeLine(‘ label parameter ‘) with console.timeLineEnd(‘ label parameter ‘) records a timeLine over a period of time.

We know from the console.timeStamp method above that we can record session information for the current page in the Performance panel, while we can only record session information for a certain period of time through console.timeline and console.timelineEnd.

// Record the session information for the first time'Test cycle 1 million related performance analysis')
for (let i = 0; i < 1000000; i ++) {}
console.timelineEnd('Test cycle 1 million related performance analysis'// Record the session information for the second period console.timeline('Test cycle 10 million related performance analysis')
for (let i = 0; i < 10000000; i ++) {}
console.timelineEnd('Test cycle 10 million related performance analysis')Copy the code

In our Performance panel, click Start Recording the current page and see the results after recording:



Console.timeline (‘ parameter label ‘) and console.timelineend (‘ parameter label ‘), both methods need to receive the same parameter label, which is just an identifier.

With this usage here, it’s more about how to do Performance analysis in Performance and find the bottlenecks that affect the Performance of the application that are important.


Having a strong console family will help us in the development and debugging process. Simple use of console content is the first step to getting started with debugging, but more powerful is the flexible use of Google’s debug panel, and more advanced automated testing.


If feel like ❤❤❤ once!!