If you're like me, you often reach for console.log
for debugging your JavaScript applications. Here's a few tricks to make logging data a little nicer.
console.count
: prints a string with the number of callsconsole.table
: prints an array of data in a tabular formatconsole.group
: organize related logs in a nested block.console.time
: start a timer to track how long an operation takes.The following is the easiest way to log out some data. The downside is that logged out data is not labeled in the console.
const name = 'John';
console.log(name); //=> 'John'
The solution? Assuming you are logging out variables, wrap them in an object.
const firstName = 'John';
const lastName = 'Sylvain';
console.log({ firstName, lastName });
//=> { firstName: 'John' , lastName: 'Sylvain' }
Consider the following example. You may want to log the data in the filter
method.
data
.map(item => item.name)
.filter(Boolean)
.reduce(...);
console.log()
has a return value of undefined
when called. When used with a logical or operator, you can log the data inline.
data
.map(item => item.name)
.filter(console.log || Boolean)
.reduce(...);
This could be useful in functional React components.
const Component = (props) => console.log({ props }) || (
<div>{props.name}</div>
);