DEV Community

Clément
Clément

Posted on

The only console.log trick I use.

My console.log trick for modern javascript

You see a lot of those console.log tricks and such detailing console.table and all that jazz.

I almost never use those, but since ES6 and single line Arrow functions poping up everywhere, it's often annoying to add simple console.log in the code without needing a bit of ceremony.

The problem:

const elements = [...Array(5).keys()]
const total = elements.reduce((total, value) => total + value)

for this code, let say I want to debug my reduce and see it in details, I would have done this:

const elements = [...Array(5).keys()]
const total = elements.reduce((total, value) => {
  console.log({ total, value })
  return total + value
})

Which is always a bit annoying, not a big deal but still, adding all those {} and I always risk to forgot the return introducing a bug when I try to debug, not ideal

A solution:

const elements = [...Array(5).keys()]
const total = elements.reduce((total, value) =>
  console.log({ total, value }) || total + value)

I just slap a || after my console.log call since it does return undefined always so this way not much changes needed to poke inside single expression arrow functions :)

Top comments (0)