DEV Community

Cover image for Our favorite javascript one-liners

Our favorite javascript one-liners

J. on January 04, 2022

These are our favorite one-liners that we've used and forgot existed because they work so well 😁. Generate a random hex color const ...
Collapse
 
lionelrowe profile image
lionel-rowe

Math.floor(Math.random() * 0xffffff) gives numbers in the range 0..0xfffffe, not 0..0xffffff. You want Math.floor(Math.random() * (0xffffff + 1)), i.e. Math.floor(Math.random() * 0x1000000) 😉

Collapse
 
stackcache profile image
J.

this guy hexes...

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Reverse string can be shortened to:

const reverseString = str => [...str].reverse().join()
Enter fullscreen mode Exit fullscreen mode

Your version also has an issue with unicode, which the above function fixes:

"🤓🚀🐍".split('').reverse().join('')   //  "\udc0d🚀🔓\ud83e"

[..."🤓🚀🐍"].reverse().join('')   // "🐍🚀🤓"
Enter fullscreen mode Exit fullscreen mode

Filtering falsy values can also be shortened:

const removeFalsyValues = arr => arr.filter(x=>x)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
stackcache profile image
J.

niiiiiice

Collapse
 
hrushalnikhare profile image
Hrushal

Cool really helped me!

Collapse
 
stackcache profile image
J.

sweet! thanks for the feedback!

Collapse
 
posandu profile image
Posandu

Cheers!

Collapse
 
stackcache profile image
J.

🔥

Collapse
 
flyingcrp profile image
flyingCrp

JavaScript's magic

Collapse
 
sergio_inge profile image
Sergio Martín

Filtering falsy values can also be done like...

const removeFalsyValues = arr => arr.filter(Boolean)

Thanks for your good article!

Collapse
 
stackcache profile image
J.

we actually had it this way originally 😄. both ways work, i think the updated one may save a character or two. i'll add a note, so that both are covered though!

Collapse
 
oricohen profile image
OriCohen05

Really cool
Thanks!

Some comments have been hidden by the post's author - find out more