DEV Community

Clément
Clément

Posted on

6 1

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

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay