DEV Community

Cover image for Our favorite javascript one-liners
J. for Everly Health

Posted on • Updated on

Our favorite javascript one-liners

These are our favorite one-liners that we've used and forgot existed because they work so well 😁.

Generate a random hex color

const color = () => '#' + Math.floor(Math.random() * (0xffffff + 1)).toString(16).padEnd(6, '0');
Enter fullscreen mode Exit fullscreen mode

Remove array duplicates

const removeDuplicates = arr => [...new Set(arr)];
Enter fullscreen mode Exit fullscreen mode

Reverse a string

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

Clear all cookies

Note: This will not always work because cookies can be set to not be changed from the front-end. (Thanks @lukeshiru!)

const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, '=;expires=${new Date(0).toUTCString()};path=/'));
Enter fullscreen mode Exit fullscreen mode

Remove falsy values from an array

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

/** OR **/

const removeFalsyValues = arr => arr.filter(Boolean)
Enter fullscreen mode Exit fullscreen mode

Get the value of a query parameter from a url

Pass in the url and the parameter that you're looking for the value of, and this function will return the value to you

const getQueryParam = (url, param) => new URL(url).searchParams.get(queryParam);
Enter fullscreen mode Exit fullscreen mode

Copy to clipboard

const copyToClipboard = (text) => navigator.clipboard.writeText(text);
Enter fullscreen mode Exit fullscreen mode

Get selected text

const getSelectedText = () => window.getSelection().toString();
Enter fullscreen mode Exit fullscreen mode

Scroll to Top

const scrollToTop = () => window.scrollTo(0, 0);
Enter fullscreen mode Exit fullscreen mode

Scroll to Bottom

const scrollToBottom = () => window.scrollTo(0, document.body.scrollHeight);
Enter fullscreen mode Exit fullscreen mode

Toggle a Boolean

const toggleBool = bool => !bool;
Enter fullscreen mode Exit fullscreen mode

Convert Fahrenheit / Celsius

const cToF = (celsius) => celsius * 9/5 + 32;
const fToC = (fahrenheit) => (fahrenheit - 32) * 5/9;
Enter fullscreen mode Exit fullscreen mode

Check if a property exists on an object

I know this seems like more than a one-liner, but given an object already exists, checking for properties on that object is definitely a one-liner 😁

const myObject = {
  id: 1,
  name: 'Tron',
  group: 'decepticons'
};

const isGroupExists = 'group' in myObject;
console.log(isGroupExists); // true

const isMusicExists = 'music' in myObject;
console.log(isMusicExists); // false
Enter fullscreen mode Exit fullscreen mode

Thanks

Special thanks to Fernando, José, @patricia_br, @lukeshiru, @lionelrowe and @jonrandy for adding to this list and optimizing!

Top comments (12)

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