Few developers go beyond the basics of browser DevTool debugging. Modesty console.log() is often ridiculed, but we all use it. This is useful for outputting values while the code is running, often to help pinpoint errors.

However, there are a number of underutilized, faster, easier, and more useful options available for client scripts, Web workers, and service workers. Node.js and Deno runtime consoles also support many features.

To open a browser DevTools F12, Ctrl | Cmd + Shift + I or Cmd + option + j and jump in.

1. Use ES6 to deconstruct assignment output variable names

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

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:


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

2. Use the appropriate log message type

Console.log () is well known:

Copy the code

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

Copy the code

Warning:

Copy the code

Error:

Copy the code

Or less important debug messages:

Copy the code

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

    propA: 1,
    propB: 2,
    propC: 3
  };

console.table( obj );
Copy the code

You can categorize a table by attribute name or value order by clicking on the associated title.

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

[1, 2, 3], [4, 5, 6], [7, 8, 9]; console.table( arr1 );Copy the code

Or array of objects:

    { 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 attributes in JavaScript objects 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.

4. Use the printf-type 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:

  '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. Modify the 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

'%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

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

Alternatively, you can use messages and replacement values:

  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:

  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. Log message groups

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) :

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 a timer

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

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

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:

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 is found 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 consolecopy() 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.