HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

JavaScript console.log() tips & tricks

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptlogtipstricksconsole

Problem

Everyone uses the JavaScript console for logging or debugging every once in a while. But there is a lot more to the console object than console.log().
ES6 computed property names are particularly useful, as they can help you identify logged variables by adding a pair of curly braces around them.
console.trace() works the exact same as console.log(), but it also outputs the entire stack trace so you know exactly what's going on.
console.group() allows you to group logs into collapsable structures and is particularly useful when you have multiple logs.
There are a few more logging levels apart from console.log(), such as console.debug(), console.info(), console.warn() and console.error().

Solution

const x = 1, y = 2, z = 3;

console.log({x, y, z}); // {x: 1, y: 2, z: 3}


console.trace() works the exact same as console.log(), but it also outputs the entire stack trace so you know exactly what's going on.
console.group() allows you to group logs into collapsable structures and is particularly useful when you have multiple logs.
There are a few more logging levels apart from console.log(), such as console.debug(), console.info(), console.warn() and console.error().
console.assert() provides a handy way to only log something as an error when an assertion fails (i.e. when the first argument is false), otherwise skip the log entirely.
You can use console.count() to count how many times a piece of code has executed.
console.time() gives you a quick way to check the performance of your code, but should not be used for real benchmarking due to its low accuracy.

Code Snippets

const x = 1, y = 2, z = 3;

console.log({x, y, z}); // {x: 1, y: 2, z: 3}
const outer = () => {
  const inner = () => console.trace('Hello');
  inner();
};

outer();
/*
  Hello
  inner @ VM207:3
  outer @ VM207:5
  (anonymous) @ VM228:1
*/
console.group('Outer');           // Create a group labelled 'Outer'
console.log('Hello');             // Log inside 'Outer'
console.groupCollapsed('Inner');  // Create a group labelled 'Inner', collapsed
console.log('Hellooooo');         // Log inside 'Inner'
console.groupEnd();               // End of current group, 'Inner'
console.groupEnd();               // End of current group, 'Outer'
console.log('Hi');                // Log outside of any groups

Context

From 30-seconds-of-code: console-log-cheatsheet

Revisions (0)

No revisions yet.