This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021


As we all know, browser developer tools provide us with a powerful debugging system, can be used to view DOM tree structure, CSS style debugging, animation debugging, JavaScript code breakpoint debugging and so on. Today we’ll take a look at some useful debugging tips for Console debugging.

Nowadays, the development of our projects usually uses React, Vue and other front-end frameworks, and front-end debugging becomes more difficult. Besides React Dev Tools, Vue Dev Tools and other plug-ins, we mostly use console.log(). Of course, in most cases, Console.log () is fine for our purposes, but as the data gets more complex, console.log() becomes a little one-dimensional. The console object provides a number of methods for printing. Here are the methods in the Console object (Chrome 95.0.4638.54 (official) (arm64)) :

The Console object provides an interface for debugging the browser console and can be accessed from any global object. If you use console.log() to output variables, you may not be using the power of Console. Now I’ll take you to console for fancy debugging.

First, basic printing

1. console.log()

Console.log () is the most basic and common usage. It can be used anywhere in the JavaScript code, and then the printed information can be seen in the browser console. The basic usage method is as follows:

let name = "CUGGZ";
let age = 18;
console.log(name)                    // CUGGZ
console.log(`my name is: ${name}`)   // CUGGZ
console.log(name, age)               // CUGGZ 18
console.log("message:", name, age)   // message: CUGGZ 18
Copy the code

In addition, console.log() supports the following output:

let name = "CUGGZ";
let age = 18;
let height = 180;
console.log('Name: %s, Age: %d', name, age)     // Name: CUGGZ, Age: 18
console.log('Age: %d, Height: %d', age, height) // Age: 18, Height: 180
Copy the code

The following variable is assigned to the position of the preceding placeholder, and they correspond one to one. This writing method can ensure the separation of template and data in complex output, and the structure is clearer. But if it’s simple output, there’s no need to write this. In console.log, the following placeholder formats are supported:

  • The value is %s
  • Integer: % d
  • Floating point: %f
  • Object: %O or %O
  • CSS style: % C

As you can see, it also supports defining CSS styles in addition to the most basic types:

let name = "CUGGZ";
console.log('My Name is %cCUGGZ'.'color: skyblue; font-size: 30px; ') 
Copy the code

Print the following (which doesn’t seem to be useful) :

Where this style might be useful is to print pictures to see if they are correct:

console.log('%c '.'background-image:url("http://iyeslogo.orbrand.com/150902Google/005.gif"); background-size:120% 120%; background-repeat:no-repeat; background-position:center center; line-height:60px; padding:30px 120px; ');
Copy the code

The print result is as follows:

Strictly speaking, console.log() does not support printing images, but you can use CSS background images to print images. However, you can’t print images directly because you can’t set the width and height properties of images, so you need to use line-heigh and padding to make them appear properly.

We can use console.log() to print character drawings like zhihu’s:

You can use the character drawing online generation tool and paste the generated characters into console.log(). Online tool: mg2txt. My avatar looks like this, with the generated characters in the middle:

In addition, you can see that when a placeholder represents an object, there are two ways to write it: %c or %c. What’s the difference between the two? There is no difference between the two objects when the object we specify is a normal object, but there is a difference when it is a DOM node.

As you can see, %o prints the contents of the DOM node, including its children. %O prints the object properties of the DOM node and can be optionally printed as required.

2. console.warn()

The console.warn() method is used to print warnings on the console. It is used in exactly the same way as console.log, except that it is displayed differently, with a yellow triangle at the top of the message to indicate a warning:

const app = ["facebook"."google"."twitter"];
console.warn(app);
Copy the code

The print style is as follows:

3. console.error()

Console.error () can be used to print error messages on the console. It is the same as the above two methods, but the display style is different:

const app = ["facebook"."google"."twitter"];
console.error(app);
Copy the code

Note that console.exception() is an alias for console.error(), and they do the same thing.

Of course, console.error() has one more feature that console.log() does not have, and that is to print the function call stack:

function a() {
  b();
}
function b() {
  console.error("error");
}
function c() {
  a();
}
c();
Copy the code

The print result is as follows:

As you can see, the function call stack is printed: b→ A → C.

The console object provides a special method to print the function’s call stack (console.trace()), which is described below.

4. console.info()

Console.info () can be used to print information class descriptions. It is used in the same way as console.log(), and prints the same effect:

Two, printing time

1. console.time() & console.timeEnd()

If we want to get the execution time of a piece of code, we can use the console.time() and console.timeend () methods of the console object, for example:

console.time();

setTimeout(() = > {
	console.timeEnd();
}, 1000);

/ / the default: 1001.9140625 ms
Copy the code

They can both pass a single parameter, which is a string that marks a unique timer. If the page has only one timer, you don’t need to pass this parameter. If there are multiple timers, you need to use this tag to mark each timer:

console.time("timer1");
console.time("timer2");

setTimeout(() = > {
	console.timeEnd("timer1");
}, 1000);

setTimeout(() = > {
	console.timeEnd("timer2");
}, 2000);

// timer1: 1004.666259765625 ms
// timer2: 2004.654052734375 ms
Copy the code

2. console.timeLog()

Console.timeend () is similar to console.timelog () here, but there are some differences. They both need to use console.time() to start a timer. Then console.timelog () is the current time of the print timer, and console.timeend () is the time of the print timer until it ends. Here’s an example:

console.time("timer");

setTimeout(() = > {
    console.timeLog("timer")
		setTimeout(() = > {
	    console.timeLog("timer");
    }, 2000);
}, 1000);

/ / timer: 1002.80224609375 ms
/ / timer: 3008.044189453125 ms
Copy the code

With console.timeend () :

console.time("timer");

setTimeout(() = > {
  console.timeEnd("timer")
	setTimeout(() = > {
	    console.timeLog("timer");
    }, 2000);
}, 1000);
Copy the code

The print result is as follows:

As you can see, it terminates the current timer, so the timeLog inside cannot find the timer counter again. So the difference between the two is whether it terminates the current timer.

Three, group printing

1. console.group() & console.groupEnd()

These two methods are used to create an information group on the console. A complete grouping of information starts with console.group() and ends with console.groupend (). Consider the following example:

console.group();
console.log('First Group');
console.group();
console.log('Second Group')
console.groupEnd();
console.groupEnd();
Copy the code

The print result is as follows:

Let’s do a more complicated one:

console.group("Alphabet")
  console.log("A");
  console.log("B");
  console.log("C");
  console.group("Numbers");
    console.log("One");
    console.log("Two");
  console.groupEnd("Numbers");
console.groupEnd("Alphabet");
Copy the code

The print result is as follows:

As you can see, these groups can be nested. Currently we need to debug a bunch of debug output, so we can choose to use grouped output,

2. console.groupCollapsed()

Console.groupcollapsed () methods are similar to console.group() and both need console.groupend () to end groups. The difference is that this method prints information folded out by default, while group() is expanded by default. To rewrite the above example:

console.groupCollapsed("Alphabet")
  console.log("A");
  console.log("B");
  console.log("C");
  console.groupCollapsed("Numbers");
    console.log("One");
    console.log("Two");
  console.groupEnd("Numbers");
console.groupEnd("Alphabet");
Copy the code

The print result is as follows:

As you can see, the only difference is that the printed result is folded and needs to be expanded manually.

Four, printing times

1. console.count()

You can use console.count() to get the current number of executions. Consider the following example:

for (i = 0; i < 5; i++) {
    console.count();
}

// The output is as follows
default: 1
default: 2
default: 3
default: 4
default: 5
Copy the code

It can also pass an argument to mark it (if empty, the default tag is default) :

for (i = 0; i < 5; i++) {
    console.count("hello");
}

// The output is as follows
hello: 1
hello: 2
hello: 3
hello: 4
hello: 5
Copy the code

This method is used in complex scenarios where a function is called in more than one place to determine whether the method is called infrequently or repeatedly.

2. console.countReset()

As the name suggests, console.countreset () is a reset calculator, which will need to be used in conjunction with the console.count() method above. It has an optional parameter label:

  • If the label argument is provided, this function resets the count associated with the label, resetting count to 0.
  • If the label argument is omitted, this function resets the default counter, resetting count to 0.
console.count(); 
console.count("a"); 
console.count("b"); 
console.count("a"); 
console.count("a"); 
console.count(); 
console.count(); 
  
console.countReset(); 
console.countReset("a"); 
console.countReset("b"); 
  
console.count(); 
console.count("a"); 
console.count("b");
Copy the code

The print result is as follows:

default:1
a:1
b:1
a:2
a:3
default:2
default:3
default:1
a:1
b:1
Copy the code

Five, other printing

1. console.table()

Console. log () allows you to easily print the properties of an array object. The result is a table. The console.table() method takes two arguments. The first argument is the object to print and the second argument is the title of the table to print, which is the property value of the array object. Consider the following example:

const users = [ 
   { 
      "first_name":"Harcourt"."last_name":"Huckerbe"."gender":"Male"."city":"Linchen"."birth_country":"China"
   },
   { 
      "first_name":"Allyn"."last_name":"McEttigen"."gender":"Male"."city":"Ambelókipoi"."birth_country":"Greece"
   },
   { 
      "first_name":"Sandor"."last_name":"Degg"."gender":"Male"."city":"Mthatha"."birth_country":"South Africa"}]console.table(users, ['first_name'.'last_name'.'city']);
Copy the code

The print result is as follows:

In this way, you can see the specified properties in the array object more clearly.

In addition, you can use console.table() to print array elements:

const app = ["facebook"."google"."twitter"];
console.table(app);
Copy the code

The print result is as follows:This way, we can see the elements of the array more clearly.

Note that console.table() can only handle a maximum of 1000 rows, so it may not fit all datasets. But it works in most scenarios.

2. console.clear()

Console.clear () clears information from the console. When the Console is cleared, “Console was clered” is printed:

Of course, we can clear the console by using the console’s clear button:

3. console.assert()

The console.assert() method is used for statement assertions, and when the assertion is false, prints an error message to the console. Its syntax is as follows:

console.assert(expression, message)
Copy the code

It takes two arguments:

  • Expression: conditional statement. The statement will be parsed to Boolean and false will trigger message output.
  • Message: Output statement, which can be of any type.

This method prints the message when the expression conditional statement is false. The console.assert() method can be used when a statement is output only in a specific case.

For example, if the number of children of a list element is greater than or equal to 100, print an error message:

console.assert(list.childNodes.length < 100."Node count is > 100");
Copy the code

The output result is as follows:

4. console.trace()

The console.trace() method can be used to print the call path on the stack for the currently executing code. It does the same work as console.error() above, but prints the same as console.log(). Consider the following example:

function a() {
  b();
}
function b() {
  console.trace();
}
function c() {
  a();
}
c();
Copy the code

The print result is as follows:

As you can see, the call stack is printed: b→ A → C, starting from the call location.

5. console.dir()

The console.dir() method displays the properties of the specified JavaScript object in the console through an interactive list that resembles a file tree. Its syntax is as follows:

console.dir(object);
Copy the code

It takes an object and eventually prints out all of its properties and property values.

In most cases, using consoledir() has the same effect as using console.log(). But when printing element structures, there is a big difference. Console.log () prints the element’s DOM structure, while console.dir() prints the element’s attributes:

6. console.dirxml()

The console.dirxml() method is used to display an explicit XML/HTML element interaction tree with all descendant elements. If it cannot be displayed as an Element, it will be displayed as a JavaScript object instead. The output is an inherited extended list of nodes that lets you see the contents of the child nodes. The syntax is as follows:

console.dirxml(object);
Copy the code

This method prints out XML elements and their descendants, and calls to console.log() and console.dirxml() are equivalent for XML and HTML elements.

7. console.memory

Console. memory is a property of the console object, not a method. It can be used to check the current memory usage. Too much console.log() will take up too much memory and cause the browser to stall.