JS

console.log tricks

John Sylvain - June 26, 2019

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.

Built-in methods

Easy labeling

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

Inline logging

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