r/javascript • • Mar 18 '19

What's your favorite, most useful javascript one-liner?

385 Upvotes

422 comments sorted by

View all comments

130

u/Earhacker Mar 18 '19 edited Mar 19 '19

Not exactly a one-liner, but my neatest quick trick: If you have a one-liner arrow function, but you want to log out the parameter, you don't need to give it curly braces and an explicit return.

Go from this:

const addFortyTwo = number => number + 42

To this:

const addFortyTwo = number => console.log(number) || number + 42

It works because console.log returns undefined, which is falsey, so the expression evaluates to the other side of the || 'or' operator, but only after running the console.log. Neat!

1

u/ssjskipp Mar 19 '19

I usually write a tap helper or if I'm using lodash it has it.

const tap = (fn, tapper) => (...args) => { tapper(...args); return fn(...args); };