Most developers have only a rudimentary knowledge of browser DevTool debugging.

The most used console.log() is useful for outputting values while the code is running, often to help pinpoint errors.

However, there is another advanced usage that many people are not aware of and therefore underutilized, faster, easier, and more useful advanced usage for client scripts, Web workers, and service workers.

Node.js and Deno runtime consoles also support many features.

1. Deconstruct the output variable names using ES6

Logging can be complicated when monitoring multiple values. It is often necessary to add more information, for example

const x = 42;

console.log('variableX:', variableX);
// or
console.log(`variableX: ${ variableX }`);

/*
output:
variableX: 42
*/
Copy the code

A faster option is to use ES6 object destruction allocation. This adds the variable to the object with the matching attribute name.

In other words, just place {and} parentheses on a variable to display its name and value:

console.log({ variableX });

/*
output:
{ variableX: 42 }
*/
Copy the code

2. Use the appropriate log message type

Console.log () is known as the simplest method:

console.log('no-frills log message');
Copy the code

But it’s not the only type. Messages can be categorized as information (as with console.log()) :

console.info('this is an information message');
Copy the code

warnings:

console.warn('I warned you this could happen! ');
Copy the code

errors:

console.error('I\'m sorry Dave, I\'m afraid I can\'t do that');
Copy the code

Or less important debug debug messages:

console.debug('nothing to see here - please move along');
Copy the code

Console.table () can output object values in a more friendly format:

const obj = {
    propA: 1.propB: 2.propC: 3
  };

console.table( obj );
Copy the code

Console.table () can also be used with one-dimensional or multidimensional arrays:

const arr1 = [
    [ 1.2.3 ],
    [ 4.5.6 ],
    [ 7.8.9]].console.table( arr1 );
Copy the code

Or array of objects:

const arr2 = [
    { a: 1.b: 2.c: 3 },
    { a: 4.b: 5.c: 6 },
    { a: 7.b: 8.c: 9}];console.table( arr2 );
Copy the code

Other options include:

  • console.dir( obj )Displays an interactive list of properties in a JavaScript object
  • console.dirxml( element )Displays an interactive tree of descendant elements from the specified HTML or XML node
  • console.clear()Clear all previous messages from the console.

3. Filter log messages

The browser displays the log messages in appropriate colors, but it can also be filtered to display specific types.

Click the icon in the upper left of the console panel to open the sidebar of Chrome:

Note that console.debug() only displays messages when viewing detailed options.

Use 4.printf-typeThe message

All logging types can use the C-style Printf message format, which defines templates with % indicators that are used to replace variables.

Such as:

console.log(
  'The answer to %s is %d.'.'life, the universe and everything'.42
);
// The answer to life, the universe and everything is 42.
Copy the code

5. Record style

Log messages can be styled using standard CSS passed as a string in the second argument of any message type.

The tag in the %c message indicates where the style is applied, for example

console.log(
  '%cOK, things are really bad now! '.` font-size: 2em; Padding: 0.5 em 2 em; margin: 1em 0; color: yellow; background-color: red; border-radius: 50%; `
);
Copy the code

The result in the DevTools console is:

6. Use assertions like tests

Console.assert () When a condition fails, you can use a command like test to output a message.

You can use a condition to define an assertion and then output one or more objects when the condition fails, for example

console.assert(
  life === 42.'life is expected to be'.42.'but is set to',
  life
);
Copy the code

Alternatively, you can use messages and replacement values:

console.assert(
  life === 42.'life is expected to be %s but is set to %s'.42,
  life
);
Copy the code

Both options display assertion errors when the condition fails:

7. Run the stack trace

You can print the log console.trace() for all function calls that make up the current point of execution with the following command:

function callMeTwo() {
  console.trace();
  return true;
}

function callMeOne() {
  return callMeTwo();
}

const r = callMeOne();
Copy the code

The trace shows the line for each call, which can be collapsed or expanded in the Console pane:

8. Group log messages

You can use console.group(label) at the beginning and at the end of console.groupend () to group log messages into named groups.

Message groups can be nested, collapsed, or expanded (console.groupCollapsed(label) initially shows collapsed groups) :

// start log group
console.group('iloop');

for (let i = 3; i > 0; i--) {

  console.log(i);

  // start collapsed log group
  console.groupCollapsed('jloop');

  for (let j = 97; j < 100; j++) {
    console.log(j);
  }

  // end log group (jloop)
  console.groupEnd();

}

// end log group (iloop)
console.groupEnd();
Copy the code

9. Use performance timers

The time(label) command starts a timer. TimeEnd (label) reports the elapsed time in milliseconds when it reaches the associated command.

Timers can be used to assess the performance of operations – easier and more accurate than managing your own Date() calculations, for example

// start timer
console.time('bigloop');

for (let i = 999999999; i > 0; i--);

// show elapsed time
console.timeEnd('bigloop');
Copy the code

Up to 10,000 timers can be added to a page, and the console.timelog (label) command reports the elapsed time without stopping the timer.

A similar option is console.count(label) reporting the number of times the command was called.

Console. countReset(label) resets the named counter to zero.

10. Debug and monitor functions by name

The DevTools Sources panel (or Debugger in Firefox) allows you to open a file and set a breakpoint by clicking a line number.

Chrome-based browsers also allow you to set breakpoints by typing debug(functionName) in the console, for example

debug( doSomething );
Copy the code

This function must be available in the global namespace, and the browser will start it immediately after the debugger is called. You can undebug using undebug(functionName) or by reloading the page.

The monitor(functionName) and its associated unmonitor(functionName) commands are used in a similar manner. Instead of stopping execution, they log each call to the function and display the arguments passed:

function doSomething called with arguments:"hello2 ",Copy the code

11. Find and fix event listeners

The Firefox DevTools inspector panel displays an event icon next to any DOM element that has a handler attached.

Click the icon to see the feature name, and then click the arrow icon to the left to expand the code.

In addition, the “Open in Debugger” icon finds handlers in the debugger pane, so you can set breakpoints:

Chrome’s implementation isn’t ideal, but you can view all event listeners by passing DOM nodes to the getEventListeners() function. For example, getEventListeners($0) show listeners applied to the DOM node currently highlighted in the Elements panel:

12. Copy properties to the clipboard

The console copy() command copies any value to the clipboard. It can be raw values, arrays, objects, or DOM nodes.

After passing the DOM node, copy() places the HTML for that element and all its children on the clipboard.

This is equivalent to right-clicking a node, then selecting copy, and then selecting Copy external HTML.

This command copies (document.documentElement) the entire HTML document. You can paste it into a text editor to make the markup easy to read.

The last

The browser DevTools has evolved from a basic console to a sophisticated development and debugging environment.

Console.log () will always be popular, but other options may provide a faster, easier way to achieve zero errors!

12 Ways to Improve Your DevTools Console Logging

Past pure text

  • Vue3 Family buckets + Element Plus + Vite + TypeScript + Eslint Project configuration best practices

  • 10 Advanced Tips for Improving Happiness in TypeScript

Welcome to pay attention to the public number: “full stack cultivation”, reply to “e-book” that you can get the following 300 technical elite books oh, cat brother WX: CB834301747.

After reading this article, if you gain anything, please click “like” or “view”. This will be my motivation to continue sharing. Thanks ~